LCA Tarjan
初二学完忘了QAQ,今天再学一发
原题Link:https://www.luogu.org/problem/show?pid=3379
Code:
1 #include <iostream> 2 #include <cstdio> 3 const int maxn=500000*2+100; 4 int n,m,i,to[maxn],root,x,y,last[maxn],next[maxn],next1[maxn],last1[maxn],to1[maxn],ans[maxn],fa[maxn],v[maxn]; 5 using namespace std; 6 inline void read(int &k) 7 { 8 int f=1;char c=getchar();k=0; 9 while (c<'0'||c>'9')c=='-'&&(f=-1),c=getchar(); 10 while (c>='0'&&c<='9')k=k*10+c-'0',c=getchar(); 11 k*=f; 12 } 13 inline int gf(int now) 14 { 15 return fa[now]==now?now:fa[now]=gf(fa[now]); 16 } 17 inline void dfs(int now) 18 { 19 v[now]=1; 20 for(int cur=last[now];cur;cur=next[cur]) 21 { 22 if (!v[to[cur]]) 23 { 24 dfs(to[cur]); 25 fa[to[cur]]=now; 26 } 27 } 28 for (int cur=last1[now];cur;cur=next1[cur]) 29 if (v[to1[cur]])ans[(cur+1)>>1]=gf(to1[cur]); 30 } 31 int main() 32 { 33 read(n);read(m);read(root); 34 for (i=1;i<n;i++) 35 { 36 read(x);read(y); 37 to[i*2-1]=y; 38 next[i*2-1]=last[x]; 39 last[x]=i*2-1; 40 to[i*2]=x; 41 next[i*2]=last[y]; 42 last[y]=i*2; 43 } 44 for (i=1;i<=m;i++) 45 { 46 read(x);read(y); 47 to1[i*2-1]=y; 48 next1[i*2-1]=last1[x]; 49 last1[x]=i*2-1; 50 to1[i*2]=x; 51 next1[i*2]=last1[y]; 52 last1[y]=i*2; 53 } 54 for (i=1;i<=n;i++)fa[i]=i; 55 dfs(root); 56 for (i=1;i<=m;i++) 57 printf("%d\n",ans[i]); 58 }