bzoj5165 树上倍增(lca)

104 篇文章 0 订阅
11 篇文章 0 订阅

这题真的就是个倍增求lca囧
不过卡空间。。。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
#define N 3000001
#define ll long long
#define inf 0x3f3f3f3f
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,fa[N][21],dep[N];
char op[5];
inline int lca(int x,int y){
    if(dep[x]<dep[y]) swap(x,y);
    int d=dep[x]-dep[y];
    for(int i=0;(1<<i)<=d;++i)
        if(d>>i&1) x=fa[x][i];
    if(x==y) return x;
    for(int i=20;i>=0;--i)
        if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i];
    return fa[x][0];
}
int main(){
//  freopen("a.in","r",stdin);
    int m=read();n=1;
    while(m--){
        scanf("%s",op+1);
        if(op[1]=='A'){
            int x=read();++n;fa[n][0]=x;dep[n]=dep[x]+1;
            for(int i=1;i<=n;++i){
                if(!fa[n][i-1]) break;
                fa[n][i]=fa[fa[n][i-1]][i-1];
            }continue;
        }int k=read()-1,x=read();
        while(k--){
            int y=read();if(x!=1) x=lca(x,y);
        }printf("%d\n",x);
    }return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值