简单LCA:
求树上距离给定两个点a,b距离相等的点有多少个
先预处理出每一个节点的孩子个数sum[x],求出a,b的LCA,根据深度就能够知道两个点的距离,距离为偶数的有解....
根据lca在a,b之间的位置不同分情况讨论:
设a与lca距离为 ha , b与lca距离为 hb
1:lca在a,b正中间既a,b分别属于lca的两个子树中, 结果为: n-sum[ a往上距离lca ha⑴ 的点] - sum[ b往上距离lca hb⑴ 的点]
2:a,b两个点相对lca1上1下. c:a,b中靠下的那个点 结果为: sum[lca]-sum[ c往上距离lca hc⑴ 的点 ]
用倍增法求LCA O(logn) , 总时间复杂度 O(mlogn)
A and B are preparing themselves for programming contests.
The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n?-?1corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.
Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.
As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.
The first line contains integer n (1?≤?n?≤?105) ― the number of rooms in the University.
The next n?-?1 lines describe the corridors. The i-th of these lines (1?≤?i?≤?n?-?1) contains two integers ai and bi (1?≤?ai,?bi?≤?n), showing that the i-th corridor connects rooms ai and bi.
The next line contains integer m (1?≤?m?≤?105) ― the number of queries.
Next m lines describe the queries. The j-th of these lines (1?≤?j?≤?m) contains two integers xj and yj (1?≤?xj,?yj?≤?n) that means that on thej-th day A will write the contest in the room xj, B will write in the room yj.
In the i-th (1?≤?i?≤?m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.
in the first sample there is only one room at the same distance from rooms number 2 and 3 ― room number 1.