簡(jiǎn)單LCA:
求樹(shù)上距離給定兩個(gè)點(diǎn)a,b距離相等的點(diǎn)有多少個(gè)
先預(yù)處理出每一個(gè)節(jié)點(diǎn)的孩子個(gè)數(shù)sum[x],求出a,b的LCA,根據(jù)深度就能夠知道兩個(gè)點(diǎn)的距離,距離為偶數(shù)的有解....
根據(jù)lca在a,b之間的位置不同分情況討論:
設(shè)a與lca距離為 ha , b與lca距離為 hb
1:lca在a,b正中間既a,b分別屬于lca的兩個(gè)子樹(shù)中, 結(jié)果為: n-sum[ a往上距離lca ha⑴ 的點(diǎn)] - sum[ b往上距離lca hb⑴ 的點(diǎn)]
2:a,b兩個(gè)點(diǎn)相對(duì)lca1上1下. c:a,b中靠下的那個(gè)點(diǎn) 結(jié)果為: sum[lca]-sum[ c往上距離lca hc⑴ 的點(diǎn) ]
用倍增法求LCA O(logn) , 總時(shí)間復(fù)雜度 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.