zoukankan      html  css  js  c++  java
  • 树的重心 POJ_1655

    //#include <bits/stdc++.h>
    
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int N;                // 1<= N <= 20000
    const int maxn = 20000;
    vector<int> tree[maxn + 5];           // tree[i]表示节点i的相邻节点
    int d[maxn + 5];                // d[i]表示以i为根的子树的节点个数
    
    #define INF 10000000
    
    int minNode;
    int minBalance;
    
    void dfs(int node, int parent) // node and its parent
    {
        d[node] = 1; // the node itself
        int maxSubTree = 0; // subtree that has the most number of nodes
        for (int i = 0; i < tree[node].size(); i++) {
            int son = tree[node][i];
            if (son != parent) {
                dfs(son, node);
                d[node] += d[son];
                maxSubTree = max(maxSubTree, d[son]);
            }
        }
        maxSubTree = max(maxSubTree, N - d[node]); // "upside substree with (N - d[node]) nodes"
    
        if (maxSubTree < minBalance){
            minBalance = maxSubTree;
            minNode = node;
        }
    }
    
    int main()
    {
        int t;
        cin >> t;
        while (t--){
            cin >> N;
    
            for (int i = 1; i <= N - 1; i++){
                tree[i].clear();
            }
    
            for (int i = 1; i <= N-1; i++){
                int u, v;
                cin >> u >> v;
                tree[u].push_back(v);
                tree[v].push_back(u);
            }
    
            minNode = 0;
            minBalance = INF;
    
            dfs(1, 0);                // fist node as root
            cout << minNode << " " << minBalance << endl;
        }
    
        return 0;
    }
    
    作者:LightAc
    出处:https://www.cnblogs.com/lightac/
    联系:
    Email: dzz@stu.ouc.edu.cn
    QQ: 1171613053
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    设计工具
    makefile介绍1.0
    cpp命名空间
    第二课 生活智慧
    第一课 我想找到好工作,我想挣钱
    php CURL
    apache 改变文档根目录www的位置
    yii2 模块的创建及使用
    yii2 源码分析Action类分析 (六)
    yii2 源码分析 model类分析 (五)
  • 原文地址:https://www.cnblogs.com/lightac/p/10585324.html
Copyright © 2011-2022 走看看