On the tree

LCA: Tree section, multiplication, Tarjan

  • Tree section - O (logn) (n < = 10 ^ 6)

  • https://www.cnblogs.com/cangT-Tlan/p/8846408.html

  • The tree is divided into a chain of several, to maintain a data structure of each chain

  • #include<bits/stdc++.h>
    #define ll long long
    #define rll register ll
    #define M 0x3f3f3f
    #define For(i,l,r) for(int i=l;i<=r;i++)
    using namespace std; 
    ll n,m,s,head[M],a[M],x,y,z,tot,k,t;
    ll fa[M],d[M],top[M],size[M],id[M],ril[M];
    struct node1{
        ll to,nxt;
    }e[M<<1];
    struct node2{
        ll l,r,sum,flag;
    }tree[M<<1];
    
    inline ll read(){
        ll f=1,sum=0;
        char ch=getchar();
        while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
        while(isdigit(ch)){sum=(sum<<1)+(sum<<3)+(ch^48);ch=getchar();}
        return f*sum;
    }
    
    inline void add(ll x,ll y){
        e[++tot].to=y;
        e[tot].nxt=head[x];
        head[x]=tot;
    }
    
    inline void dfs1(ll u){//Dfs first pass through the tree, the depth d pretreatment, size this point node number, its parent node FA 
        d [U] = d [FA [U]] + . 1 ; 
        size [U] = . 1 ;
         for (I = RLL head [U]; I; I = E [I] .nxt) {
             IF ! (E [I] .to = FA [U]) { 
                FA [E [I] .to] = U; 
                DFS1 (E [I ] .to); 
                size [U] + = size [E [I] .to]; 
            } 
        } 
    } 
    
    inline void DFS2 (U LL) { // the number of child nodes according to the severity of side division number, ensure that only a point in a chain. Usually only the heavy side and light side less than. 
        T = LL 0 ; // Top i.e. points where the edges for this vertex heavy  
        IF Top [U] = (Top [U]!) U;
         for(RLL head I = [U]; I; I = E [I] .nxt) {
             IF (! E [I] .to FA = [U] && size [E [I] .to]> T) T = E [I] .to; 
        } 
        IF (T) { 
            Top [T] = Top [U]; 
            DFS2 (T); 
        } 
        for (RLL head I = [U]; I; I = E [I] .nxt) {
             iF (!! E [I] .to FA = [U] && E [I] .to = T) DFS2 (E [I] .to); 
        } 
    } 
    
    inline LCA LL (LL X, Y LL) { // when two points are located on a heavy chain that is the same operation is ended. Otherwise skip to point deeper depth where a point on the heavy chain, shallow depth position at the end point of the operation is also desired LCA
         the while (Top [X]! = Top [Y]) {
             IF (D [Top [X ]] < D [Top [Y]]) the swap (X, Y); 
            X = FA [Top [X]]; 
        } 
        IF(d[x]>d[y]) swap(x,y);
        return x;
    }
    
    int main(){
        n=read(),m=read(),s=read();
        For(i,1,n-1) {x=read(),y=read(),add(x,y),add(y,x);}
        dfs1(s),dfs2(s);
        For(i,1,m){x=read(),y=read(),printf("%lld\n",lca(x,y));}
        return 0;
    }
  • topic:

  1. Hamster find sugar

     

     

Guess you like

Origin www.cnblogs.com/wi1d3on/p/11330532.html