ACdream1015 Double Kings(dfs)

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值