Graph Theory37 sections · 1633 units
Open in Course

CSES 1133 Tree Distances II - Problem Statement

CSES 1133

You are given a tree with nn nodes. For each node, calculate the sum of distances from that node to all other nodes. This is harder than Tree Distances I because sum is not max.

You cannot use diameter endpoints. This problem requires rerooting DP: compute the answer for root, then update incrementally when you move the root to each child. When you shift the root from parent to child, some nodes get 11 closer and others get 11 farther. Track subtree sizes to compute these shifts in O(1)O(1) per edge.