tarjanLCA求树上任意两点间的距离。。。。
任意选一个点当根节点,dist[a,b]= dist[a] +dist[b] -2* lca[a,b]
2 3 2 1 2 10 3 1 15 1 2 2 3 2 2 1 2 100 1 2 2 1
10 25 100 100
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; const int maxn=44000; struct Edge { int to,next,distan; }edge[2*maxn],edge2[maxn]; int Adj[maxn],Adj2[maxn],Size,Size2; void init_1() { Size=0; memset(Adj,-1,sizeof(Adj)); } void init_2() { Size2=0; memset(Adj2,-1,sizeof(Adj2)); } void Add_Edge(int u,int v,int c) { edge[Size].to=v; edge[Size].next=Adj[u]; edge[Size].distan=c; Adj[u]=Size++; } void Add_Edge2(int u,int v,int id) { edge2[Size2].to=v; edge2[Size2].next=Adj2[u]; edge2[Size2].distan=id; Adj2[u]=Size2++; } int n,m; int fa[maxn]; int Find(int x) { if(x==fa[x]) return x; return fa[x]=Find(fa[x]); } bool vis[maxn]; int Distan[maxn],ans[maxn]; void LCA(int u,int father) { for(int i=Adj[u];~i;i=edge[i].next) { int v=edge[i].to; if(v==father) continue; Distan[v]=Distan[u]+edge[i].distan; LCA(v,u); fa[v]=u; } vis[u]=true; for(int i=Adj2[u];~i;i=edge2[i].next) { int v=edge2[i].to; int id=edge2[i].distan; if(vis[v]) { ans[id]=Distan[u]+Distan[v]-2*Distan[Find(v)]; } } } int main() { int T_T; scanf("%d",&T_T); while(T_T--) { init_1();init_2(); scanf("%d%d",&n,&m); fa[0]=0;fa[1]=1;fa[2]=2; for(int i=0;i<n-1;i++) { int a,b,c; scanf("%d%d%d",&a,&b,&c); Add_Edge(a,b,c); Add_Edge(b,a,c); fa[i+3]=i+3; } for(int i=0;i<m;i++) { int a,b; scanf("%d%d",&a,&b); Add_Edge2(a,b,i); Add_Edge2(b,a,i); } memset(Distan,0,sizeof(Distan)); memset(ans,0,sizeof(ans)); memset(vis,false,sizeof(vis)); LCA(1,1); for(int i=0;i<m;i++) printf("%d\n",ans[i]); } return 0; }