Topic Connection
http://acm.hdu.edu.cn/showproblem.php?pid=2586
How far away? Description
There is n houses in the village and some bidirectional roads connecting them. Every day peole "What is it if I am want to go from House A to house B"? Usually it hard to answer. But luckily int this village the answer was always unique, since the roads was built in the the-the-the-that-there is a unique simp Le path ("simple" means you can ' t visit a place twice) between every the houses. Yout task is to answer all these curious people.
Input
First line was a single integer T (t<=10), indicating the number of test cases.
For each test case,in the first line there is the numbers N (2<=n<=40000) and M (1<=m<=200), the number of hous Es and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning this there is a road con Necting House I and House j,with length K (0<k<=40000). The houses is labeled from 1 to N.
Next m lines each have distinct integers i and j, you areato answer the distance between House I and House J.
Output
For each test case,output m lines. Each line represents the answer of the query. Output a bland line after all test case.
Sample Input
2
3 2
1 2 10
3 1 15
1 2
2 3
2 2
1 2 100
1 2
2 1
Sample Output
10
25
100
100
tarjan offline for LCA.
#include <bits/stdc++.h>using namespace Std;const int N = 40010;struct TARJAN_LCA {bool Vis[n]; Vector<pair<int, int>> A, q[n]; int tot, par[n], ans[210], head[n], dist[n]; struct Edge {int to, w, next;} G[n << 1]; inline void init (int n) {a.clear (); for (int i = 0; i < n + 2; i++) {par[i] = i; Vis[i] = false; Head[i] =-1; Dist[i] = 0; Q[i].clear (); }}: inline void Add_edge (int u, int v, int w) {G[tot] = {V, W, Head[u]}, head[u] = tot++; G[tot] = {u, W, Head[v]}, head[v] = tot++; } inline void built (int n, int m) {int u, V, W; while (n--> 1) {scanf ("%d%d%d", &u, &v, &w); Add_edge (U, V, W); } for (int i = 0; i < m; i++) {scanf ("%d%d", &u, &v); A.push_back (Pair<int, int> (U, v)); Q[u].push_back (Pair<int, int> (V, i)); Q[v].push_back (Pair<int, int> (U, i)); }} inline int find (int x) {while (x = Par[x]) {x = par[x] = par[par[x]]; } return x; } inline void Tarjan (int u, int fa) {for (int i = head[u]; ~i; i = g[i].next) {Edge &e = G[i]; if (e.to = = FA) continue; Dist[e.to] = Dist[u] + e.w; Tarjan (e.to, u); Vis[e.to] = true; Par[e.to] = u; } for (auto &r:q[u]) {if (Vis[r.first]) Ans[r.second] = find (R.first); }} inline void solve (int n, int m) {init (n); Built (n, m); Tarjan (1, 1); for (int i = 0; i < m; i++) {printf ("%d\n", Dist[a[i].first] + Dist[a[i].second]-2 * dist[ans[i]]); }}}go;int Main () {#ifdef LOCAL freopen ("In.txt", "R", stdin); Freopen ("OUT.txt", "w+", stdout); #endif int T, n, M; scanf ("%d", &t); while (t--) {scanf ("%d%d", &n, &m); Go.solve (n, m); } return 0;}
HUD 2586 how far away?