hdu-2586 http://acm.hdu.edu.cn/showproblem.php?pid=2586
// meaning of the questions: a village there are n houses, only one path between two houses, and the village is China Unicom. Q m queries distance between the two houses, the answer to the query output every time. n (2 <= n <= 40000) m (1 <= m <= 200)
. 1 #include <cstdio> 2 #include <CString> . 3 #include <algorithm> . 4 the using namespace STD; . 5 . 6 const int MAXN = 4e4 + . 5 ; . 7 . 8 struct Node { // V will be appreciated that for the current node, and u can be is understood to father node . 9 int U, v, W, Next; // W is a two u-> v is from 10 } Edge [ 2 * MAXN]; // undirected graph for a 2 * . 11 12 is int n-, m; 13 is int NUM = . 1 ; // number of nodes 14 int head [ 2 * MAXN]; // used to map a node ID value 15 int Deep [MAXN]; // a point in the depth (tree) 16 int F [MAXN] [ 21 is ]; // F [ i] [J] denotes the i 2 ^ j ancestors . 17 int G [MAXN]; // save distance from a point to the root of 18 is . 19 void add_edge member ( int X, int Y, int Z) { // contribution 20 is Edge [NUM] .u = X; 21 is Edge [NUM] .v = Y; 22 is Edge [NUM] .W = Z; 23 is Edge [NUM] = .next head [X]; 24 head [X] NUM = ++ ; 25 } 26 is 27 void DFS ( int CUR) { // calculates each node's father node number, depth, and the roots distance 28 for ( int I = head [CUR]; I = -! . 1 ; I = Edge [I] .next) { 29 IF (Deep [Edge [I] .v] == 0 ) { 30 Deep [Edge [I] .v] = Deep [CUR] + . 1 ; 31 is F [Edge [I] .v] [ 0 ] = CUR; 32 G [Edge [I] .v] = G [CUR] + Edge [I] .w; 33 dfs(edge[i].v); 34 } 35 } 36 } 37 38 void PRE() {// 倍增求f[i][j] 39 for(int j = 1; j <= 19; ++j) { 40 for(int i = 1; i <= n; ++i) { 41 f[i][j] = f[f[i][j-1]][j-1]; 42 } 43 } 44 } 45 46 int LCA(int x, int y) {// 倍增思想 47 if(deep[x] < deep[y]) swap(x, y); 48 for(int i = 19; i >= 0; --i) { 49 if(deep[f[x][i]] >= deep[y]) { 50 x = f[x][i]; 51 } 52 } 53 if(x == y) return x; 54 for(int i = 19; i >= 0; --i) { 55 if(f[x][i] != f[y][i]) { 56 x = f[x][i]; 57 y = f[y][i]; 58 } 59 } 60 return f[x][0]; 61 } 62 63 int main() { 64 int T; 65 scanf("%d", &T); 66 while(T--) { 67 memset(head, -1, sizeof(head)); 68 memset(deep, 0, sizeof(deep)); 69 memset(f, 0, sizeof(f)); 70 memset(g, 0, sizeof(g)); 71 72 scanf("%d%d", &n, &m); 73 int s, e, v; 74 for(int i = 0; i != n-1; ++i) { 75 scanf("%d%d%d", &s, &e, &v); 76 add_edge(s, e, v); 77 add_edge(e, s, v); 78 } 79 deep[1] = 1; 80 dfs(1); 81 PRE(); 82 for(int i = 0; i != m; ++i) { 83 scanf("%d%d", &s, &e); 84 printf("%d\n", g[s]+g[e]-2*g[LCA(s, e)]);// 画图即可理解 85 } 86 } 87 return 0; 88 }