链接:
http://poj.org/problem?id=1986
代码:
31 struct edge { int to, weight; }; 32 vector<edge> G[MAXN]; 33 int vs[MAXN * 2 - 1]; 34 int depth[MAXN * 2 - 1]; 35 int id[MAXN]; 36 int dist[MAXN]; 37 38 int bit[MAXN * 2 - 1][16]; 39 40 void rmq_init(int n) { 41 rep(i, 0, n) bit[i][0] = i; 42 for (int j = 1; (1 << j) < n; j++) 43 for (int i = 0; i + (1 << j) - 1 < n; i++){ 44 if (depth[bit[i][j - 1]] <= depth[bit[i + (1 << (j - 1))][j - 1]]) 45 bit[i][j] = bit[i][j - 1]; 46 else bit[i][j] = bit[i + (1 << (j - 1))][j - 1]; 47 } 48 } 49 50 int query(int l, int r) 51 { 52 int k = 0; 53 while ((1 << (k + 1)) < r - l + 1) k++; 54 if (depth[bit[l][k]] <= depth[bit[r - (1 << k)][k]]) 55 return bit[l][k]; 56 else return bit[r - (1 << k)][k]; 57 } 58 59 void dfs(int v, int p, int d, int &k) { 60 id[v] = k; 61 vs[k] = v; 62 depth[k++] = d; 63 rep(i, 0, G[v].size()) if (G[v][i].to != p) { 64 dist[G[v][i].to] = dist[v] + G[v][i].weight; 65 dfs(G[v][i].to, v, d + 1, k); 66 vs[k] = v; 67 depth[k++] = d; 68 } 69 } 70 71 void init(int V) { 72 int k = 0, root = 0; 73 dfs(root, -1, 0, k); 74 rmq_init(V * 2 - 1); 75 } 76 77 int lca(int u, int v) { 78 return vs[query(min(id[u], id[v]), max(id[u], id[v]) + 1)]; 79 } 80 81 int main() { 82 int n, m; 83 cin >> n >> m; 84 int u, v, w; 85 char c; 86 while (m--) { 87 scanf("%d%d%d %c", &u, &v, &w, &c); 88 u--, v--; 89 G[u].pb(edge{ v,w }); 90 G[v].pb(edge{ u,w }); 91 } 92 init(n); 93 int k; 94 cin >> k; 95 while (k--) { 96 int u, v; 97 scanf("%d%d", &u, &v); 98 u--, v--; 99 int t = lca(u, v); 100 int ans = dist[u] - dist[t] + dist[v] - dist[t]; 101 printf("%d ", ans); 102 } 103 return 0; 104 }