zoukankan      html  css  js  c++  java
  • P3884 [JLOI2009]二叉树问题

    题意:给你一个二叉树,输出它的深度,宽度,以及对于结点u和v输出它们的距离
    u和v的距离定义:设u和v的最近公共祖先为c,dist(u, v) = dist(u, c) * 2 + dist(v, c);

    #include<iostream>
    #include<algorithm>
    #include<cstring>
    
    using namespace std;
    
    const int N = 110;
    
    int n;
    int cnt[N], st[N];
    int h[N], e[N], ne[N], idx;
    int p[N]; // 结点的双亲结点
    int w, d; // 宽度,深度
    
    void add(int a, int b){
        e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
    }
    
    int dfs(int u, int l){
        st[u] = 1;
        cnt[l] ++;
        w = max(cnt[l], w);
        d = max(l, d);
        for(int i = h[u]; i != -1; i = ne[i]){
            int j = e[i];
            if(st[j] == 0) dfs(j, l + 1);
        }
    }
    
    int lca(int u, int v, int step1, int step2){
        if(u == v) return step1 * 2 + step2;
        if(u < v) return lca(u, p[v], step1, step2 + 1); // 根据序号大小来爬树
        return lca(p[u], v, step1 + 1, step2);
    }
    
    int main(){
        memset(h, -1, sizeof h);
        
        cin >> n;
        
        for(int i = 0; i < n - 1; i ++){
            int a, b;
            cin >> a >> b;
            
            add(a, b);
            
            p[b] = a;
        }
        
        dfs(1, 1);
        
        cout << d << endl << w << endl;
        
        int u, v;
        cin >> u >> v;
        
        cout << lca(u, v, 0, 0);
        
        return 0;
    }
    
  • 相关阅读:
    【例题 6-12 UVA
    【例题 6-11 UVA-297】Quadtrees
    【例题 6-10 UVA
    SpringMVC表单验证器
    Spring MVC常用注解
    什么是Spring Boot?
    什么是Kotlin?Java的替代语言?
    阿里Druid连接池的坑。。
    常见的3种Class级别的错误
    阿里巴巴,排行前10的开源项目
  • 原文地址:https://www.cnblogs.com/tomori/p/13873090.html
Copyright © 2011-2022 走看看