• LCA(RMQ)


    const lx=100004;
          xh=27;
    var    L,p,nt:array[0..lx*2] of longint;
        lt,dfn,fr,dep:array[0..lx] of longint;
        f:array[0..lx*2,0..xh] of longint;
        vis:array[0..lx] of boolean;
        i,x,y,n,sum,q:longint;
    procedure swap(var a,b:longint);
    var c:longint;
    begin
        c:=a; a:=b; b:=c;
    end;
    procedure dfs(u:longint);
    var i,v:longint;
    begin
        inc(sum); dfn[u]:=sum; vis[u]:=true;
        inc(L[0]); L[L[0]]:=u;
        fr[u]:=L[0];
        i:=lt[u];
        while i<>0 do
        begin
            v:=p[i];
            if not vis[v] then
            begin
                dep[v]:=dep[u]+1;
                dfs(v);
                inc(L[0]); L[L[0]]:=u;
            end;
            i:=nt[i];
        end;
    end;
    procedure prepare;
    var i,j:longint;
    begin
        fillchar(fr,sizeof(fr),0);
        fillchar(vis,sizeof(vis),false);
        fillchar(L,sizeof(L),0);
        sum:=0;
            dep[1]:=1;
        dfs(1);
        for i:=1 to L[0] do f[i,0]:=L[i];
        for i:=1 to xh do
            for j:=1 to L[0] do
                if j+1<<i-1<=L[0] then
                    if dfn[f[j,i-1]]<dfn[f[j+1<<(i-1),i-1]] then f[j,i]:=f[j,i-1]
                        else f[j,i]:=f[j+1<<(i-1),i-1];
    end;
    procedure add(x,y:longint);
    begin
        inc(sum); p[sum]:=y; nt[sum]:=lt[x]; lt[x]:=sum;
    end;
    function find(s,t:longint):longint;
    var k:longint;
    begin
        s:=fr[s]; t:=fr[t];
        if s>t then swap(s,t);
        k:=trunc(ln(t-s+1)/ln(2));
        if dfn[f[s,k]]<dfn[f[t-1<<k+1,k]] then exit(f[s,k]) else exit(f[t-1<<k+1,k]);
    end;
    function dis(s,t:longint):longint;
    var k:longint;
    begin
        k:=find(s,t);
        exit(dep[t]-dep[k]+dep[s]-dep[k]);
    end;
    begin
        readln(n);
        fillchar(lt,sizeof(lt),0);
        sum:=0;
        for i:=1 to n-1 do
        begin
            readln(x,y);
            add(x,y);
            add(y,x);
        end;
        prepare;
    
    end.
  • 相关阅读:
    忙活了半宿,写了个小玩意
    luogu P5171 Earthquake
    luogu P1850 换教室
    luogu P2507 [SCOI2008]配对 |动态规划
    luogu P3830 [SHOI2012]随机树
    luogu P3959 宝藏
    牛客竞赛-比赛
    牛客竞赛-Who killed Cock Robin
    luogu P3807 【模板】卢卡斯定理
    牛客竞赛 -被3整除的子序列
  • 原文地址:https://www.cnblogs.com/rpSebastian/p/4358872.html
Copyright © 2020-2023  润新知