zoukankan      html  css  js  c++  java
  • 二叉树问题--洛谷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
    %d
    %d
    ",deep,width,dep[u] * 2 + dep[v] - dep[o] * 3);
        return 0;
    }

    错误:

    1.多反转了

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

    2.

  • 相关阅读:
    UML
    Jenkins(Jenkins的安装配置)
    SpringCloud:Config配置中心
    IDEA将项目上传到GitHub
    JS—高阶函数
    项目中git操作
    互联网概述
    ESLint的extends
    vue3 + TS + eslint 实现代码格式化以及代码规范提示
    vue3基础使用
  • 原文地址:https://www.cnblogs.com/darlingroot/p/10617480.html
Copyright © 2011-2022 走看看