其他分享
首页 > 其他分享> > 二叉树问题--洛谷3884

二叉树问题--洛谷3884

作者:互联网

传送门

 

我jio的这基本就是一个裸的LCA

然而我debug de了好久

qwq

我简直是太傻了

 

#include<cstdio>
#include<algorithm>
using namespace std;

inline int read()
{
    int sum = 0,p = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')
            p = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        (sum *= 10)+= ch - '0';
        ch = getchar();
    }
    return sum * p;
}

const int N = 210;
int n,deep,width;
int cnt,dep[N],to[N],nxt[N],head[N],wid[N];
int fa[N][15];

void add(int x,int y)
{
    nxt[++cnt] = head[x];
    to[cnt] = y;
    head[x] = cnt;
}

void dfs(int x,int k)
{
    dep[x] = dep[k] + 1;
    deep = max(deep,dep[x]);
    fa[x][0] = k;
    for(int i = 1;(1<<i)<=dep[x];i++)
    {
        fa[x][i] = fa[fa[x][i - 1]][i - 1];
    }
    for(int i = head[x];i;i = nxt[i])
    {
        if(to[i] == fa[x][0])
            continue;
        dfs(to[i],x);
    }
}

int lca(int x,int y)
{
    if(dep[x] < dep[y])
    {
        swap(x,y);
    }
    int sum = dep[x] - dep[y];
    for(int i = 10;i >= 0;i--)
    {
        if((1<<i)<= sum)
        {
            x = fa[x][i];
            sum -= (1<<i);
        }
        if(x == y)
        return x;
    }
    for(int i = 10;i >= 0;i--)
    {
        if(fa[x][i] != fa[y][i])
        {
            x = fa[x][i];
            y = fa[y][i];
        }
    }
    return fa[x][0];
}

void find()
{
    for(int i = 1;i <= deep;i++)
        width = max(width,wid[i]);
}

int main()
{
    n = read();
    int a,b;
    for(int i = 1;i < n;i++)
    {
        a = read(),b = read();
        add(a,b);
        add(b,a);
    }
    dfs(1,0);
    for(int i = 1;i <= n;i++)
    {
        wid[dep[i]]++;
    }
    int u = read(),v = read();
    int o = lca(u,v);
    find();
    printf("%d\n%d\n%d\n",deep,width,dep[u] * 2 + dep[v] - dep[o] * 3);
    return 0;
}

 

 

错误:

1.多反转了

2.上下两个循环我换过来写的qwq,自然就炸了

2.

标签:3884,ch,洛谷,int,fa,二叉树,include,qwq,getchar
来源: https://www.cnblogs.com/darlingroot/p/10617480.html