#include<cstring>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<ctime>
using namespace std;
using namespace std;
const int N=500005;
int cnt,fa[N],ans[N],head[N],rhead[N],dis[N];
bool vis[N];
struct node{
int u,v,next,id;
}edge[N],redge[N];
int find(int x){
if(fa[x]==-1){
return x;
}
return fa[x]=find(fa[x]);
}
void Union(int a,int b){
if(find(a)!=find(b)){
fa[find(b)]=find(a);
}
}
void push1(int u,int v){
edge[cnt].u=u;
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt;
cnt++;
}
void push2(int u,int v,int id){
redge[cnt].u=u;
redge[cnt].v=v;
redge[cnt].id=id;
redge[cnt].next=rhead[u];
rhead[u]=cnt;
cnt++;
}
void tarjan(int fa){
vis[fa]=true;
for(int i=head[fa];i!=-1;i=edge[i].next){
int v=edge[i].v;
if(vis[v]){
continue;
}
tarjan(v);
Union(fa,v);
}
for(int i=rhead[fa];i!=-1;i=redge[i].next){
int v=redge[i].v;
if(vis[v]){
ans[redge[i].id]=find(v);
}
}
}
int main(){
int n,m,u,v;
memset(head,-1,sizeof(head));
memset(rhead,-1,sizeof(rhead));
memset(fa,-1,sizeof(fa));
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&m);
n-=1;
while(n--){
scanf("%d%d",&u,&v);
push1(u,v);
push1(v,u);
}
cnt=0;
for(int i=1;i<=m;i++){
scanf("%d%d",&u,&v);
push2(u,v,i);
push2(v,u,i);
}
tarjan(1);
for(int i=1;i<=m;i++){
printf("%d\n",ans[i]);
}
return 0;
}
转载于:https://www.cnblogs.com/ukcxrtjr/p/11194271.html