LCA模板整理
HDU2586 纯LCA模板
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #define lowbit(x) x&(-x) #define rep(i,l,r) for(int i=l;i<=r;++i) #define per(i,r,l) for(int i=r;i>=l;--i) #define ls o<<1 #define rs o<<1|1 #define lson L,mid,ls #define rson mid+1,R,rs #define fi first #define se second using namespace std; inline char nc() { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } inline int _read() { char ch = nc(); int sum = 0; while (!(ch >= '0'&&ch <= '9'))ch = nc(); while (ch >= '0'&&ch <= '9')sum = sum * 10 + ch - 48, ch = nc(); return sum; } typedef long long ll; const int maxn = 4e4+10; const double eps = 1e-8; const int mod = 998244353; const double pi = acos(-1.0); vector<pair<int,int>> G[maxn]; int dep[maxn],dis[maxn],par[maxn][20]; void dfs(int u,int fa,int dp,int ds) { dep[u]=dp; dis[u]=ds; if(u==1) { for(int i=0;i<20;i++)par[u][i]=1; } else { par[u][0]=fa; for(int i=1;i<20;i++) { par[u][i]=par[par[u][i-1]][i-1]; } } for(auto e:G[u]) { int v=e.fi,c=e.se; if(v==fa) continue; dfs(v,u,dp+1,ds+c); } } int Jump(int u,int ds) { for(int j=19;j>=0;j--) { if((1<<j)&ds) { u=par[u][j]; } } return u; } int lca(int u,int v) { if(dep[u]<dep[v]) swap(u,v); //u 深度较大 u=Jump(u,dep[u]-dep[v]); if(u==v) return u; for(int i=19;i>=0;i--) { if(par[u][i]!=par[v][i]) { u=par[u][i]; v=par[v][i]; } } return par[u][0]; } int main() { int T; T=_read(); while(T--) { int n,m; n=_read(),m=_read(); for(int i=1;i<n;i++) { int u,v,c; u=_read(),v=_read(),c=_read(); G[u].push_back(make_pair(v,c)); G[v].push_back(make_pair(u,c)); } dfs(1,1,0,0); for(int i=1;i<=m;i++) { int u,v; u=_read(),v=_read(); int ca=lca(u,v); printf("%d\n",dis[u]+dis[v]-2*dis[ca]); } } }