/* The nearest common ancestor of the adjacent table + LCA mainly adopts the DFS (post-traversal order) + query set (no compression path is required) method to implement the back-order backtracking process, update the Father's Day node */# include <iostream> # include <cstdio> # include <algorithm> # include <cmath> # include <vector> using namespace STD; # define Manx 40009 vector <int> V [Manx], W [Manx], que [Manx], ans_num [Manx]; bool vist [Manx]; int n, m, father [Manx], DIS [Manx], ANS [203]; void Init () {for (INT I = 0; I <= N; I ++) {v [I]. clear (); W [I]. clear (); que [I]. clear (); ans_num [I]. clear (); Vist [I] = 0; father [I] = I; DIS [I] = 0 ;}} int find (INT X) {return x = Father [x]? X: Father [x] = find (father [x]);} void Union (int x, int y) {FATHER [find (y)] = find (x );} void Tarjan (INT now, int Val) {vist [now] = true; DIS [now] = val; For (INT Len = V [now]. size (), I = 0; I <Len; I ++) {int temp = V [now] [I]; If (vist [temp]) continue; tarjan (temp, Val + W [now] [I]); Union (now, temp);} For (INT Len = que [now]. size (), I = 0; I <Len; I ++) {int temp = que [now] [I]; If (! Vist [temp]) continue; ans [ans_num [now] [I] = dis [now] + dis [temp]-2 * Dis [find (temp)];} int main () {int t, q; scanf ("% d", & T); While (t --) {scanf ("% d", & N, & Q); Init (); int A, B, C; For (INT I = 1; I <n; I ++) {scanf ("% d", & A, & B, & C); V [A]. push_back (B); V [B]. push_back (a); W [A]. push_back (c); W [B]. push_back (c) ;}for (INT I = 0; I <q; I ++) {scanf ("% d", & A, & B ); que [A]. push_back (B); que [B]. push_back (a); ans_num [A]. push_back (I); ans_num [B]. push_back (I);} Tarjan (1, 0); For (INT I = 0; I <q; I ++) printf ("% d \ n ", ans [I]) ;}}
Link: http://blog.csdn.net/keroro520/article/details/9131857