LCA的模板题目,今天才发现自己其实对LCA这个算法一点都没领悟。之前一直是在套模板,所以今天的主要目标就是学习一下tarjan算法求LCA,顺便刷点LCA的相关习题来加强理解~
1 #include <cstdio> 2 #include <algorithm> 3 4 int dis[1005],head[2333],fa[1100][21],deep[1005]; 5 int Count,n,q; 6 7 8 struct node{ 9 int v,next,w; 10 node(){} 11 node(int _v,int _next,int _w){ 12 v = _v; 13 next = _next; 14 w = _w; 15 } 16 }Edge[2333]; 17 18 void AddEdge(int u,int v,int w){ 19 Count++; 20 Edge[Count] = node(v,head[u],w); 21 head[u] = Count; 22 } 23 24 void dfs(int now,int f){ 25 for(int i=head[now];i;i=Edge[i].next){ 26 if(f==Edge[i].v) continue; 27 deep[Edge[i].v] = deep[now]+1; 28 fa[Edge[i].v][0]=now; 29 dis[Edge[i].v]=dis[now]+Edge[i].w; 30 dfs(Edge[i].v,now); 31 } 32 } 33 34 int lca(int x,int y){ 35 if(deep[x]<deep[y]) std::swap(x,y); 36 int k = deep[x] - deep[y]; 37 for(int i=20;i>=0&&k;i--){ 38 if((1<<i)&k){ 39 x = fa[x][i]; 40 k-=(1<<i); 41 } 42 } 43 if(x==y) return x; 44 for(int i=20;i>=0;i--){ 45 if(fa[x][i]!=fa[y][i]){ 46 x = fa[x][i]; 47 y = fa[y][i]; 48 } 49 } 50 if(x!=y) x = fa[x][0]; 51 return x; 52 } 53 54 int main(){ 55 //freopen("fuckyou.out","w",stdout); 56 scanf("%d%d",&n,&q); 57 for(int i=1;i<n;i++){ 58 int x,y,w; 59 scanf("%d%d%d",&x,&y,&w); 60 AddEdge(x,y,w); 61 AddEdge(y,x,w); 62 } 63 dfs(1,-1); 64 for(int j=1;j<=20;j++) 65 for(int i=1;i<=n;i++) 66 fa[i][j] = fa[fa[i][j-1]][j-1]; 67 while(q--){ 68 int x,y; 69 scanf("%d%d",&x,&y); 70 printf("%d\n",dis[x]+dis[y]-2*dis[lca(x,y)]); 71 } 72 return 0; 73 }
时间: 2024-11-29 03:21:03