树链剖分dfs2死循环求助
查看原帖
树链剖分dfs2死循环求助
740948
rb_tree楼主2025/2/6 16:22

rt,

#include<cstdio>
#define int long long
using namespace std; 
inline int read()
{
    int x=0,w=1;
    char ch=0;
    while(ch<'0'||ch>'9')
    {
        if(ch=='-') w=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9')
    {
        x=(x<<1)+(x<<3)+(ch^48);
        ch=getchar();
    }
    return x*w;
}
inline void write(int x) 
{
    if(x<0) 
    { 
        x=-x;
        putchar('-');
    }
    if(x>=10) write(x/10);
    putchar((x%10)^48);
}
int to[500005],nxt[500005],h[500005],_cnt;
void add_edge(int u,int v)
{
    to[++_cnt]=v;
    nxt[_cnt]=h[u];
    h[u]=_cnt;
}
int fa[500005],son[500005],siz[500005],top[500005],dep[500005];
void dfs1(int u)
{
    son[u]=-1;
    siz[u]=1;
    for(int i=h[u];i;i=nxt[i])
    {
        int v=to[i];
        if(!dep[v])
        {
            fa[v]=u;
            dep[v]=dep[u]+1;
            dfs1(v);
            siz[u]+=siz[v];
            if(son[u]==-1||siz[v]>siz[son[u]]) son[u]=v;
        }
    }
}
void dfs2(int u,int t)
{
    top[u]=t;
    if(son[u]==-1) return;
    dfs2(son[u],t);
    for(int i=h[u];i;i=nxt[i])
    {
        int v=to[i]; 
        if(v!=son[u]&&v!=fa[u]) dfs2(v,v);
    }
}
signed main()
{
    int n=read(),m=read(),root=read();
    for(int i=1;i<n;i++)
    {
        int u=read(),v=read();
        add_edge(u,v);
        add_edge(v,u);
    }
    dfs1(root);
    dfs2(root,root);
    for(int i=1;i<=m;i++)
    {
        int x=read(),y=read();
        while(top[x]!=top[y])
        {
            if(dep[top[x]]>dep[top[y]]) x=fa[top[x]];
            else y=fa[top[y]];
        }
        write(dep[x]>dep[y]?y:x);
        putchar('\n');
    }
    return 0;
}
2025/2/6 16:22
加载中...