您的位置:首页 > 其它

LCA之tarjan模板

2017-07-18 10:19 239 查看
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
const int maxx=500010;
int be[maxx],ne[maxx*2],to[maxx*2],e=0;
int bee[maxx],nee[maxx*2],too[maxx*2],w[maxx*2],ee=0;
int ans[maxx],fa[maxx],root;
bool p[maxx];
void ad(int x,int y){
to[++e]=y;
ne[e]=be[x];
be[x]=e;
}
void add(int x,int y,int z){
too[++ee]=y;
nee[ee]=bee[x];
bee[x]=ee;
w[ee]=z;
}
int find(int x){
return fa[x]=fa[x]==x?x:find(fa[x]);
}
void dfs(int id){
p[id]=1;
fa[id]=id;
for(int u=be[id];u;u=ne[u]){
int go=to[u];
if(!p[go]){
dfs(go);
fa[go]=id;
}
}
for(int u=bee[id];u;u=nee[u]){
int go=too[u];
if(p[go])
ans[w[u]]=find(go);
}
}
int read(){
char x;
while((x = getchar()) > '9' || x < '0') ;
int u = x - '0';
while((x = getchar()) <= '9' && x >= '0') u = u * 10 + x - '0';
return u;
}
int main(){
#ifndef ONLINE_JUDDGE
freopen("input.in","r",stdin);
freopen("output.out","w",stdout);
#endif
int i,j,k,m,n;
n=read();
m=read();
root=read();
for(i=1;i<n;i++){
j=read();
k=read();
ad(j,k);
ad(k,j);
}
for(i=1;i<=m;i++){
j=read();
k=read();
add(j,k,i);
add(k,j,i);
}
dfs(root);
for(i=1;i<=m;i++)
printf("%d\n",ans[i]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: