Sum of shortest paths
Practice
3.1 (7 votes)
Algorithms
Combinatorics
Depth first search
Graphs
Math
Medium
Problem
58% Success 874 Attempts 50 Points 2s Time Limit 256MB Memory 1024 KB Max Code
Consider that \(D(G,u,v)\) is defined as the number of edges on the shortest path from \(u\) to \(v\) in a graph \(G\).
You are given a tree \(T\) with \(N\) vertices and \(Q\) queries of the following type:
- If we add edge \((a,b)\) to the tree \(T\), obtaining graph \(G_1\), then what is the value of \(\sum_{1 \le u < v \le N} D(G_1,u,v)\)?
Note: The queries are independent in nature.
Input format
- First line: Two integers - \(N,Q\) \((1 \le N \le 2^{18}, 1 \le Q \le 2 \cdot 10^5)\)
- \(N - 1\) lines: Two integers - \(x\) and \(y\) \((1 \le x,y \le N)\) representing that there exists an edge \((x,y)\) in the tree \(T\)
- Next \(Q\) lines: Two integers - \(a\) and \(b\) \((1 \le a,b \le N, D(T,a,b) > 1)\) representing the query where a new edge \((a,b)\) is added
Output format
Print \(Q\) lines where the \(i^{th}\) line contains the answer for the \(i^{th}\) query in the chronological order.
Additional information
- For \(10\) points: \(N,Q \le 128\) should be satisfied
- For additional \(50\) points: \(D(T,a,b) \le 16\)
- For additional \(30\) points: \(\sum_{(a,b)} D(T,a,b) \le 8 \, 500 \, 000\)
- For additional \(10\) points: \(Q \le 10^5\). Note that it is not guaranteed that this subtask has a solution under the given time limit.
Submissions
Please login to view your submissions
Similar Problems
Points:50
16 votes
Tags:
AlgorithmsBit manipulationCombinatoricsDepth First SearchDynamic ProgrammingGraphsLowest Common AncestorTrees
Points:50
2 votes
Tags:
AlgorithmsDepth First SearchGraphsMedium
Points:50
3 votes
Tags:
AlgorithmsApprovedGraphsMediumTrees
Editorial