ACdream 1015 Double Kings【贪心*2】

来源:互联网 发布:openstack基础网络 编辑:程序博客网 时间:2024/06/13 11:43

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 2
2 3
3 4

4
1 2
1 3
1 4
Sample Output
2
3

题意:给出一个树,大王子先对某一个点染色,二儿子其后。每一个节点的市长会选择离他们更近的染色点的主人作为国王。
问:大王子最多能让多少个节点支持他。

分析:每一个节点,不是支持大王子就是支持二王子。大王子的目标是,选择一个节点进行染色,然后其森林中节点数目最多的子树从整体而言是最小的。二儿子没办法,只能在大儿子指定的森林中选择节点个数最大的子树的根节点进行染色。

据说大儿子染色的那个点就是树的重心,不过无所谓,时间复杂度没差。

#include<iostream>#include<cstdio>#include<iomanip>#include<cstring>#include<vector>#include<algorithm>#include<functional>using namespace std;#define INF 0x3f3f3f3fconst int maxn = 5 * 1e4 + 10;int ans, n;vector<int> G[maxn];int dfs(int x, int f){    int Max = 1; int tmp = 0; int MG = 0;    for (int i = 0; i < G[x].size(); i++)    {        if (G[x][i] == f)            continue;        tmp = dfs(G[x][i], x);//当前森林里的某树节点个数        Max += tmp;        MG = max(MG, tmp);    }    MG = max(MG, n - Max);    ans = min(ans, MG);    return Max;//包括自己}int main(){    while (~scanf("%d", &n))    {        int u, v;        for (int i = 0; i <= n; i++)        {            G[i].clear();        }        for (int i = 1; i <= n - 1; i++)        {            scanf("%d%d", &u, &v);            G[u].push_back(v);            G[v].push_back(u);        }        ans = INF;        dfs(1, 0);        printf("%d\n", n - ans);    }    return 0;}