1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include<vector> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int N = 20010, M = N * 2; typedef pair<int, int> PII;
int n, m; int h[N], e[M], ne[M], w[M], idx; int dist[N]; int ans[N]; int st[N]; int p[N]; vector<PII> query[N];
void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ; }
void dfs(int u, int father) { for(int i = h[u]; i != -1; i = ne[i]) { int j = e[i]; if(j == father) continue; dist[j] = dist[u] + w[i]; dfs(j, u); } }
int find(int x) { if(p[x] != x) p[x] = find(p[x]); return p[x]; }
void Tarjan(int u) { st[u] = 1; for(int i = h[u]; i != -1; i = ne[i]) { int j = e[i]; if(!st[j]) { Tarjan(j); p[j] = u; } } for(auto item : query[u]) { int t = item.first, id = item.second; if(st[t] == 2) { int anc = find(t); ans[id] = dist[u] + dist[t] - dist[anc] * 2; } } st[u] = 2; }
int main() { scanf("%d%d", &n, &m); memset(h, -1, sizeof h); for(int i = 1; i < n; i ++ ) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c), add(b, a, c); } dfs(1, -1); for(int i = 1; i <= m; i ++ ) { int a, b; scanf("%d%d", &a, &b); if(a != b) { query[a].push_back({b, i}); query[b].push_back({a, i}); } } for(int i = 1; i <= n; i ++ ) p[i] = i; Tarjan(1); for(int i = 1; i <= m; i ++ ) printf("%d\n", ans[i]); return 0; }
|