首页 > 其他 > 详细

树的重心 POJ_1655

时间:2019-03-23 20:21:38      阅读:134      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

技术分享图片

//#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;
}

 

树的重心 POJ_1655

原文:https://www.cnblogs.com/lightac/p/10585324.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!