BZOJ4281: [ONTAK2015]Związek Harcerstwa Bajtockiego

SBLCA

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;
#define ll int
const
 int maxn=1000001;

struct Chain
{
    ll u;
    Chain *next;
}*Head[maxn];
ll Dep[maxn];
ll f[maxn][21];
void DFS(ll u,ll fa)
{f[u][0]=fa;
  for(Chain*tp=Head[u];tp;tp=tp->next)if(tp->u^fa){Dep[tp->u]=Dep[u]+1;DFS(tp->u,u);}}




inline int min(int a,int b)
{return a<b?a:b;}
inline int max(int a,int b)
{return a>b?a:b;}
inline void Add(int u,int v)
{
  Chain*tp=new Chain;tp->next=Head[u];tp->u=v;Head[u]=tp;
}
char c;
inline void read(ll &a)
{
    a=0;do c=getchar();while(c<'0'||c>'9');
    while(c<='9'&&c>='0')a=(a<<3)+(a<<1)+c-'0',c=getchar();
}

int Up(int x,int d)
{
   int y=Dep[x]-d,i;
   while(Dep[x]^y)
    {
      for(i=0;Dep[f[x][i+1]]>=y&&i<20;i++);
      x=f[x][i];
    }
return x;
}
inline int LCA(int x,int y)
{
  if(Dep[x]<Dep[y])swap(x,y);
  int i;
   while(Dep[x]^Dep[y])
    {
      for(i=0;Dep[f[x][i+1]]>=Dep[y]&&i<20;i++);
      x=f[x][i];
    }
    while(x^y)
    {
      for(i=0;f[x][i+1]!=f[y][i+1]&&i<20;i++);
      x=f[x][i],y=f[y][i];
    }
return x;
}

int main()
{
    int T;
    ll n,m,i,j,k,t,l,d,s,K;
    read(n),read(m),read(K);
    for(i=1;i<n;i++)
      read(j),read(k),Add(j,k),Add(k,j);
    DFS(n,n);    
    int pos=m;
    for(int i=1;i<=20;i++)
      for(int j=1;j<=n;j++)f[j][i]=f[f[j][i-1]][i-1];
    while(K--)
    {
      read(d),read(s);
      int LC=LCA(pos,d);
      if(Dep[d]+Dep[pos]-2*Dep[LC]<=s)printf("%d ",pos=d);
      else
        if(Dep[pos]-Dep[LC]>=s)printf("%d ",pos=Up(pos,s));
      else printf("%d ",pos=Up(d,Dep[d]+Dep[pos]-2*Dep[LC]-s));
    }
    return 0;
}

你可能感兴趣的:(BZOJ4281: [ONTAK2015]Związek Harcerstwa Bajtockiego)