tarjan求LCA模板
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<string> #include<queue> using namespace std; int n,m; int f[400001],lin1[400001],lin2[400001],len1=0,len2=0; bool vis[400001]; struct one { int y,next,zhi; }; one e1[400001]; one e2[400001]; void insert1(int aa,int bb) { e1[++len1].next=lin1[aa]; lin1[aa]=len1; e1[len1].y=bb; } void insert2(int aa,int bb) { e2[++len2].next=lin2[aa]; lin2[aa]=len2; e2[len2].y=bb; } int findit(int p) { while(p!=f[p]) { p=f[p]; } return p; } void Tarjan(int p) { vis[p]=true; for(int i=lin1[p];i;i=e1[i].next) { if(vis[e1[i].y])continue; Tarjan(e1[i].y); f[e1[i].y]=p; } for(int i=lin2[p];i;i=e2[i].next) { if(vis[e2[i].y]) e2[i].zhi=findit(e2[i].y); } } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=m*2;i++)e2[i].zhi=0; for(int i=1;i<=n;i++) { f[i]=i; vis[i]=false; } for(int i=1;i<=n-1;i++) {int aa,bb; scanf("%d%d",&aa,&bb); insert1(aa,bb); insert1(bb,aa); } for(int i=1;i<=m;i++) { int aa,bb; scanf("%d%d",&aa,&bb); insert2(aa,bb); insert2(bb,aa); } vis[1]=true; Tarjan(1); for(int i=1;i<=m*2;i+=2) { cout<<max(e2[i].zhi,e2[i+1].zhi)<<endl; } return 0; }