最近公共祖先LCA tarjan
来源:互联网 发布:抗韩中年人淘宝外设店 编辑:程序博客网 时间:2024/06/05 20:45
/* 最近公共祖先LCA tarjan by sbn*/#include<iostream>#include<cstdio>#include<cstring>using namespace std;struct edge{ int x,y,nxt; edge(){} edge(int nx,int ny,int nnxt){ x=nx;y=ny;nxt=nnxt; }} E[1000001],Q[1000001];int n,m,root,cnte,cntq,lca[1000001];int s,father[500001];bool vis[500001];int heade[500001],headq[500001];inline void link_e(int x,int y){ E[++cnte]=edge(x,y,heade[x]); E[++cnte]=edge(y,x,heade[y]); heade[x]=cnte-1; heade[y]=cnte;}inline void link_q(int x,int y){ Q[++cntq]=edge(x,y,headq[x]); headq[x]=cntq; Q[++cntq]=edge(y,x,headq[y]); headq[y]=cntq;}int getfather(int x){ if (father[x]==x) return x; father[x]=getfather(father[x]); return father[x];}void dfs(int x){ vis[x]=1; int k=heade[x]; while (k!=0){ if (!vis[E[k].y]) {dfs(E[k].y);father[getfather(E[k].y)]=getfather(x);} k=E[k].nxt; } k=headq[x]; while (k!=0){ if (vis[Q[k].y]) lca[(k+1)/2]=getfather(Q[k].y); k=Q[k].nxt; }}int read(){ int x=0;char ch=getchar(); while(ch<'0'||ch>'9')ch=getchar(); while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar(); return x;}int main(){ //freopen("tarjan.txt","r",stdin); n=read(); m=read(); s=read(); for (int i=1;i<=n-1;i++) { int a=read(),b=read(); link_e(a,b); } //freopen("tarjan.txt","w",stdout); for (int i=1;i<=n;i++) father[i]=i; for (int i=1;i<=m;i++) { int a=read(),b=read(); link_q(a,b); } //cout<<cntq<<endl; dfs(s); for (int i=1;i<=cntq/2;i++) printf("%d\n",lca[i]); return 0; }
阅读全文