dfs
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N=1e5+5;
vector<int> g[N];
int deep[N],p[N];
void dfs(int u,int x,int pos)
{
p[u]=x;
deep[u]=pos;
for(int i:g[u])
{
if(i!=x)
{
dfs(i,u,pos+1);
}
}
}
int lca(int u,int v)
{
while(deep[u]>deep[v])u=p[u];
while(deep[v]>deep[u])v=p[v];
while(u!=v)u=p[u],v=p[v];
return u;
}
int main()
{
int n;cin>>n;
for(int i=1,u,v;i^n;i++)
{
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1,-1,0);
int x,y;
cin>>x>>y;
printf("%d\n",lca(x,y));
}
tarjan
/*
* @Author: qin_peng
* @Date: 2018-10-10 21:21:51
* @Last Modified by: qin_peng
* @Last Modified time: 2018-10-11 16:13:23
*/
#include<bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef unsigned long long ull;
const int N=500005;
int vis[N],f[N],ans[N];
vector<int>g[N],p[N],q[N];
int father(int x)
{
return f[x]==x?x:f[x]=father(f[x]);
}
void F(int x,int y)
{
int fx=father(x),fy=father(y);
if(fx!=fy)f[fx]=fy;
}
void tarjan(int u)
{
vis[u]=1;
for(int i:g[u])
{
if(!vis[i])
{
tarjan(i);
F(i,u);
}
}
for(int i=0;i<q[u].size();i++)
{
if(vis[q[u][i]])
{
ans[p[u][i]]=father(q[u][i]);
}
}
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0;i<=n;i++)f[i]=i;
for(int i=1,u,v;i^n;i++)
{
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
for(int i=1,u,v;i<=m;i++)
{
scanf("%d%d",&u,&v);
q[u].push_back(v);
q[v].push_back(u);
p[u].push_back(i);
p[v].push_back(i);
}
tarjan(1);
for(int i=1;i<=m;i++)
printf("%d\n",ans[i]);
}
const int maxx = 500000 + 100;
int head[maxx],depth[maxx];
int n,m,x,y,root,num;
int grand[maxx][20+2];
bool done[maxx];
struct Edge{
int next;
int to;
}Edges[maxx<<1];
inline int Read(){
int x=0,f=1;char c=getchar();
while(c>'9'||c<'0') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=x*10+c-'0'; c=getchar();}
return x*f;
}
void Add(int x,int y){
Edges[++num].to=y;
Edges[num].next=head[x];
head[x]=num;
}
void Dfs(int x){
done[x]=true;
for(int i=1;i<=20;i++){
if(depth[x] < (1<<i)) break;
grand[x][i]=grand[grand[x][i-1]][i-1];
}
for(int i=head[x];i;i=Edges[i].next){
int now=Edges[i].to;
if(done[now]) continue;
depth[now]=depth[x]+1;
grand[now][0]=x;
Dfs(now);
}
}
void Lca(int x,int y){
if(depth[x]>depth[y]) swap(x,y);
int d=depth[y]-depth[x];
for(int i=0;i<=20;i++){
if((1<<i) & d)
y=grand[y][i];
}
for(int i=20;i>=0;i--){
if(grand[x][i]!=grand[y][i]){
x=grand[x][i];
y=grand[y][i];
}
}
printf("%d\n",x==y? x:grand[x][0]);
}
int main(){
n=Read();m=Read();root=Read();
for(int i=1;i<n;i++){
x=Read();y=Read();
Add(x,y);
Add(y,x);
}
Dfs(root);
while( m-- ){
x=Read();y=Read();
Lca(x,y);
}
return 0;
}
点
F[l]++,F[r]++,F[lca(l,r)]--,F[grand[lca(l,r)][0]]--;
边
F[l]++,F[r]++,F[lca(l,r)]-=2;
©著作权归作者所有:来自51CTO博客作者qinXpeng的原创作品,如需转载,请注明出处,否则将追究法律责任
lca51cto数据结构
共同学习,写下你的评论
评论加载中...
作者其他优质文章