acdream 1015 Double Kings(树的重心)

来源:互联网 发布:巫师3卡顿优化补丁 编辑:程序博客网 时间:2024/06/05 19:41

 Double Kings

Time Limit: 2000/1000MS (Java/Others)    Memory Limit: 128000/64000KB (Java/Others)
Submit Status

Problem Description

Our country is tree-like structure, that is to say that N cities is connected by exactly N - 1 roads.
The old king has two little sons. To make everything fairly, he dicided to divide the country into two parts and each son get one part. Two sons can choose one city as their capitals. For each city, who will be their king is all depend on whose capital is more close to them. If two capitals have the same distance to them, they will choose the elder son as their king. 
(The distance is the number of roads between two city)
The old king like his elder son more, so the elder son could choose his capital firstly. Everybody is selfish, the elder son want to own more cities after the little son choose capital while the little son also want to own the cities as much as he can.
If two sons both use optimal strategy, we wonder how many cities will choose elder son as their king.

Input

There are multiple test cases.
The first line contains an integer N (1 ≤ N ≤ 50000).
The next N - 1 lines each line contains two integers a and b indicating there is a road between city a and city b. (1 ≤ a, b ≤ N)

Output

For each test case, output an integer indicating the number of cities who will choose elder son as their king.

Sample Input

4 1 22 33 441 21 31 4

Sample Output

23
思路:这个题主要考树的重心,知道树的重心,总数 减去 重心的最大子树的节点数 就是elder son城池的数目
#include<iostream>#include<cstdio>#include<vector>#include<algorithm>using namespace std;const int maxn=5e4+10;const int INF=0x3f3f3f3f;int n, minBalance, minNode;vector<int> tree[maxn];int d[maxn];void dfs(int node, int parent){    //cout<<1<<endl;    //cout<<node<<"****"<<endl;    d[node]=1;    int maxSubTree=0;    //cout<<tree[node].size()<<endl;    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]);    if(minBalance>=maxSubTree)    {        minBalance=maxSubTree;        minNode=node;    }    return;}int main(){    while(~scanf("%d", &n))    {        int u, v;        for(int i=1; i<=5e4; i++)            tree[i].clear();        for(int i=1; i<=n-1; i++)        {            scanf("%d%d", &u, &v);            tree[u].push_back(v);            tree[v].push_back(u);        }        minNode=0;        minBalance=INF;        dfs(1, 0);        printf("%d\n", n-minBalance);    }    return 0;}


原创粉丝点击