Dijkstra on tree

Revision en4, by Noobish_Monk, 2025-12-13 14:58:59

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.

The problem where this optimisation is used is below, though it's not the hardest part of the problem.

1859F - Teleportation in Byteland

Tags dijkstra, trees

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en5 English Noobish_Monk 2025-12-13 14:59:15 0 (published)
en4 English Noobish_Monk 2025-12-13 14:58:59 106 (saved to drafts)
en3 English Noobish_Monk 2025-12-13 14:55:24 0 (published)
en2 English Noobish_Monk 2025-12-13 14:55:01 54
en1 English Noobish_Monk 2025-12-13 14:54:12 1533 Initial revision (saved to drafts)