【题目链接】
https://www.lydsy.com/JudgeOnline/problem.php?id=1602
【算法】
倍增求LCA
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 1010 #define MAXLOG 20 int i,n,q,u,v,w; int sum[MAXN],anc[MAXN][MAXLOG],dep[MAXN]; vector< pair<int,int> > e[MAXN]; inline int lca(int u,int v) { int i,t; if (dep[u] > dep[v]) swap(u,v); t = dep[v] - dep[u]; for (i = 0; i < MAXLOG; i++) { if (t & (1 << i)) v = anc[v][i]; } if (u == v) return u; for (i = MAXLOG - 1; i >= 0; i--) { if (anc[u][i] != anc[v][i]) { u = anc[u][i]; v = anc[v][i]; } } return anc[u][0]; } inline void dfs(int u) { int i,v,w; for (i = 1; i < MAXLOG; i++) anc[u][i] = anc[anc[u][i-1]][i-1]; for (i = 0; i < e[u].size(); i++) { v = e[u][i].first; w = e[u][i].second; if (anc[u][0] != v) { dep[v] = dep[u] + 1; sum[v] = sum[u] + w; anc[v][0] = u; dfs(v); } } } int main() { scanf("%d%d",&n,&q); for (i = 1; i < n; i++) { scanf("%d%d%d",&u,&v,&w); e[u].push_back(make_pair(v,w)); e[v].push_back(make_pair(u,w)); } dfs(1); while (q--) { scanf("%d%d",&u,&v); printf("%d\n",sum[u]+sum[v]-2*sum[lca(u,v)]); } return 0; }