lca模板

// 节点编号从1开始
const lint maxn = 200000 + 10;
const lint maxm = 500000;
lint ver[maxm],ne[maxm],he[maxn],tot;
vector<lint> vex,vey;
void init(){
    memset( he,0,sizeof( he ) );
    tot = 1;
}
void add( lint x,lint y ){
    ver[++tot] = y;
    ne[tot] = he[x];
    he[x] = tot;
}
struct lca{
    lint de[maxn],anc[maxn][21];
    queue<lint> que;
    void init(){
        memset( anc,-1,sizeof( anc ) );
        while( que.size() ) que.pop();
    }
    void bfs( ){
        que.push( 1 );
        de[1] = 0;
        while( que.size() ){
            lint x = que.front();
            que.pop();
            for( lint cure = he[x];cure;cure = ne[cure] ){
                lint y = ver[cure];
                if( y == anc[x][0] ) continue;
                que.push(y);
                de[y] = de[x] + 1;
                anc[y][0] = x;
                for( lint i = 1; (1 << i) <= de[y]; i++ ){
                    anc[y][i] = anc[ anc[y][i-1] ][i-1];
            }
        }
        }
    }
    lint solve( lint x,lint y ){
       if( x == y ) return x;
        if( de[x] < de[y] ) swap( x,y );
        for( lint i = 18; i >= 0;i-- ){
            lint an = anc[x][i];
            if( an == -1 ) continue;
            if( de[an] >= de[y] ){
                x = an;
            }
        }
        if( x == y ) return y;
        for( lint i = 18; i >= 0; i-- ){
            if( anc[x][i] == -1 || anc[y][i] ==-1 ) continue;
            if( anc[x][i] != anc[y][i] ){
                x = anc[x][i];
                y = anc[y][i];
            }
        }
        return anc[x][0];
    }
}g;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值