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.

  • 相关阅读:
    把csv文件导入数据库
    c# DataTable 针对xml、excel、csv导入和导出
    ASP.NET常用珍藏代码
    C# 判断图片链接是否存在
    在asp.net中长内容自动分页的实现.NET教程
    SQL代理服务启动不了SQLSERVERAGENT
    SQL重复记录查询(转载)
    在asp.net中长内容自动分页的实现.NET教程2
    根据年月来判断月里天数
    SQL字符串函数
  • 原文地址:https://www.cnblogs.com/darlingroot/p/10617480.html
Copyright © 2011-2022 走看看