Dijkstra on tree

Правка en3, от Noobish_Monk, 2025-12-13 14:55:24

Hi everyone!

This is a pretty basic blog about dp on trees, nothing advanced. Like always, I write blogs about something which I found both not obvious while solving the problem and it's a general idea which can be used in other problems.

The problem is as follows:

A weighted tree on $$$n$$$ vertices is given, as well as $$$n$$$ values $$$d_v$$$. The task is to run Dijkstra algorithm with these initial values. Usual setup for Dijkstra is $$$d_v = \infty$$$ and $$$d_{root} = 0$$$, but here all vertices have a start value. We need to do that in $$$O(n)$$$.

Solution: Root the tree arbitrarily. All pathes in a tree look like first going up and then going down. We'll do two dfs-es, the first will relax values from children to vertex, the second will relax values from vertex to children. This way every shortest path is accounted.

Code

If we need to run a single Dijksta, $$$O(n \log n)$$$ gets TLE rarely, where $$$O(n)$$$ works. But if we need to run many Djikstras, for example, in binary search or in centroid decomposition, this will give a big speed up.

1859F - Teleportation in Byteland

Теги dijkstra, trees

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en5 Английский Noobish_Monk 2025-12-13 14:59:15 0 (published)
en4 Английский Noobish_Monk 2025-12-13 14:58:59 106 (saved to drafts)
en3 Английский Noobish_Monk 2025-12-13 14:55:24 0 (published)
en2 Английский Noobish_Monk 2025-12-13 14:55:01 54
en1 Английский Noobish_Monk 2025-12-13 14:54:12 1533 Initial revision (saved to drafts)