Sum of shortest paths

3.1

7 votes
Algorithms, Combinatorics, Depth First Search, Graphs, Math, Medium
Problem

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 G1, then what is the value of 1u<vND(G1,u,v)?

Note: The queries are independent in nature.

Input format

  • First line: Two integers - N,Q (1N218,1Q2105)
  • N1 lines: Two integers - x and y (1x,yN) representing that there exists an edge (x,y) in the tree T
  • Next Q lines: Two integers - a and b (1a,bN,D(T,a,b)>1) representing the query where a new edge (a,b) is added

Output format

Print Q lines where the ith  line contains the answer for the ith query in the chronological order.

Additional information

  • For 10 points: N,Q128 should be satisfied
  • For additional 50 points: D(T,a,b)16
  • For additional 30 points: (a,b)D(T,a,b)8500000
  • For additional 10 points: Q105. Note that it is not guaranteed that this subtask has a solution under the given time limit.
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

Above is attached tree T. The modified tree in the first query will be:

The shortest path between 4 and 6 becomes 2 compared to initial value 4. Same holds for shortest path between and 8 and 6 .

Editor Image

?