poj1330gym101808k连接



#include<map>

#include<set>

#include<cmath>

#include<queue>

#include<stack>

#include<vector>

#include<cstdio>

#include<cassert>

#include<iomanip>

#include<cstdlib>

#include<cstring>

#include<iostream>

#include<algorithm>

#define C 0.5772156649

#define pi acos(-1.0)

#define ll long long

#define mod 1000000007

#define ls l,m,rt<<1

#define rs m+1,r,rt<<1|1

#pragma comment(linker,
"/STACK:1024000000,1024000000")

 

using namespace std;

 

const double g=10.0,eps=1e-7;

const int
N=10000+10,maxn=500+100,inf=0x3f3f3f;

vector<int>v[N];

int depth[N],father[20][N];

void dfs(int u,int f,int d)

{

   
depth[u]=d;

   
for(int i=0;i<v[u].size();i++)

       
if(v[u][i]!=f)

          
dfs(v[u][i],u,d+1);

}

void init(int n)

{

   
int x=1;

   
while(father[0][x]!=-1)x=father[0][x];

   
dfs(x,-1,0);

   
for(int i=1;i<20;i++)

       
for(int j=1;j<=n;j++)

           
father[i][j]=father[i-1][father[i-1][j]];

}

int lca(int x,int y)

{

   
if(depth[x]>depth[y])swap(x,y);

   
for(int i=0;i<20;i++)

       
if((depth[y]-depth[x])>>i&1)

{cout<<depth[y]-depth[x]<<"
"<<i<<" "<<y<<"
"<<father[i][y]<<endl;y=father[i][y];}

   
if(x==y)return x;

   
for(int i=19;i>=0;i--)

    {

       
if(father[i][x]!=father[i][y])

       
{

           
x=father[i][x];

           
y=father[i][y];

       
}

    }

   
return father[0][x];

}

int main()

{

   
ios::sync_with_stdio(false);

   
cin.tie(0);

   
int t,n;

   
cin>>t;

   
while(t--){

       
cin>>n;

       
for(int i=1;i<=n;i++)v[i].clear();

       
memset(father,-1,sizeof father);

       
memset(depth,0,sizeof depth);

       
for(int i=1;i<n;i++)

       
{

           
int a,b;

           
cin>>a>>b;

           
father[0][b]=a;

           
v[a].push_back(b);

       
}

       
init(n);

       
int a,b;

       
cin>>a>>b;

       
cout<<lca(a,b)<<endl;

    }

   
return 0;

}

 


lca模板题,基本看懂,还不熟练,先放着,到时候总结模板
gym101808k代码连接https://blog.csdn.net/LSD20164388/article/details/81097000

猜你喜欢

转载自blog.csdn.net/weixin_43331783/article/details/88321406