WA #11#12 求助
查看原帖
WA #11#12 求助
223560
_HL_楼主2022/1/22 18:59

不太明白为什么会WA后两个点

#include <bits/stdc++.h>
using namespace std;
const int N=5e5+5;
#define int long long 
inline int read()
{
    int x=0;
    char c=getchar();
    while(c<'0'||c>'9')c=getchar();
    while(c<='9'&&c>='0')
    {
        x=(x<<1)+(x<<3)+c-'0';
        c=getchar();
    }
    return x;
}

struct node
{
    int nxt;
    int to;
}e[N<<1];
int tot;
int h[N];
inline void add(int x,int y)
{
    e[++tot].to=y;
    e[tot].nxt=h[x];
    h[x]=tot;
}
int t[N][100];
int dep[N];
void dfs(int x)
{
    for(int j=1;(1<<j)<=dep[x];j++)
    {
        t[x][j]=t[t[x][j-1]][j-1];
    }
    for(int i=h[x];i;i=e[i].nxt)
    {
        if(e[i].to!=t[x][0])
        {
            t[e[i].to][0]=x;
            dep[e[i].to]=dep[x]+1;
            dfs(e[i].to);
        }
    }
}
int lca(int x,int y)
{
    if(dep[x]!=dep[y])
    {
        if(dep[x]<dep[y])swap(x,y);
        for(int j=ceil(log2(dep[x]-dep[y]))+1;j>=0;j--)
        {
            if(dep[x]-(1<<j)>dep[y])x=t[x][j];
        }
        x=t[x][0];
    }
    if(x==y)return x;
    for(int j=ceil(log2(x));j>=0;j--)
    {
        if(t[x][j]!=t[y][j])
        {
            x=t[x][j];
            y=t[y][j];
        }
    }
    return t[x][0];
}
signed main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int n=read(),m=read(),s=read();
    for(int i=1;i<n;i++)
    {
        int x=read(),y=read();
        add(x,y);
        add(y,x);
    }
    dep[s]=1;
    dfs(s);
    for(int i=1;i<=m;i++)
    {
        int x=read(),y=read();
        printf("%lld\n",lca(x,y));
    }
    return 0;
}
2022/1/22 18:59
加载中...