Problem Description
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
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 cityb. (1 ≤ a, b ≤ N)
Output
Sample Input
4 1 2 2 3 3 4 4 1 2 1 3 1 4
Sample Output
2 3
没有看出来是dfs..看题解还有贪心解法
加了邻接表的dfs 第一次遇到这样的题
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 100005;
const int INF = 0x3f3f3f3f;
struct Edge
{
/* data */
int x, num, next;
}e[MAXN];
int n, num, head[MAXN], ans[MAXN];
void addedge(int x, int y)
{
++num;
e[num].x = y, e[num].num = 0;
e[num].next = head[x];
head[x] = num;
}
void dfs(int x, int f)
{
for(int i = head[x]; i != -1; i = e[i].next)
if(e[i].x != f) {
int v = e[i].x;
dfs(v, x);
for(int j = head[v]; j != -1; j = e[j].next) {
if(e[j].x == x) continue;
e[i].num += e[j].num;
}
e[i].num += 1;
e[i ^ 1].num = n - e[i].num;
}
}
int main(int argc, char const *argv[])
{
int x, y, ret;
while(scanf("%d", &n) != EOF) {
num = -1;
ret = INF;
memset(ans, 0, sizeof(ans));
memset(head, 0xff, sizeof(head));
for(int i = 1; i < n; ++i) {
scanf("%d%d", &x, &y);
addedge(x, y);
addedge(y, x);
}
dfs(1, 0);
for(int i = 1; i <= n; ++i) {
for(int j = head[i]; j != -1; j = e[j].next)
ans[i] = max(ans[i], e[j].num);
ret = min(ret, ans[i]);
}
printf("%d\n", n - ret);
}
return 0;
}
1173



被折叠的 条评论
为什么被折叠?



