HDU 1054 Strategic Game

Problem Description

Bob enjoys playing computer games, especially strategic games, but sometimes he cannot find the solution fast enough and then he is very sad. Now he has the following problem. He must defend a medieval city, the roads of which form a tree. He has to put the minimum number of soldiers on the nodes so that they can observe all the edges. Can you help him?

Your program should find the minimum number of soldiers that Bob has to put for a given tree.

The input file contains several data sets in text format. Each data set represents a tree with the following description:

the number of nodes
the description of each node in the following format
node_identifier:(number_of_roads) node_identifier1 node_identifier2 ... node_identifier
or
node_identifier:(0)

The node identifiers are integer numbers between 0 and n-1, for n nodes (0 < n <= 1500). Every edge appears only once in the input data.

For example for the tree: 

HDU 1054 Strategic Game_第1张图片 

the solution is one soldier ( at the node 1).

The output should be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the minimum number of soldiers). An example is given in the following table:

Sample Input

4
0:(1) 1
1:(2) 2 3
2:(0)
3:(0)
5
3:(3) 1 4 2
1:(1) 0
2:(0)
0:(0)
4:(0)

Sample Output

1

2

树形dp或者最大匹配。

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 1505;
vector<int> tree[maxn];
int n, x, y, z, dp[maxn][2];

void work(int x, int fa)
{
	dp[x][0] = 0; dp[x][1] = 1;
	for (int i = 0; i < tree[x].size();i++)
	if (tree[x][i] != fa)
	{
		int y = tree[x][i];
		work(y, x);
		dp[x][1] += min(dp[y][0], dp[y][1]);
		dp[x][0] += dp[y][1];
	}
}

int main()
{
	while (~scanf("%d", &n))
	{
		for (int i = 0; i < n; i++) tree[i].clear();
		for (int i = 0; i < n; i++)
		{
			scanf("%d:(%d)", &x, &z);
			while (z--)
			{
				scanf("%d", &y);
				tree[x].push_back(y);
				tree[y].push_back(x);
			}
		}
		work(0, 0);
		cout << min(dp[0][0], dp[0][1]) << endl;
	}
}
网上能找到的树形dp都是这么做的,但是其实按题意来说,这样写应该是有问题的。

0:(3) 1 2 3

1:(1) 4

2:(1) 5

3:(1) 7

4:(0)

5:(1) 6

6:(0)

7:(1) 8

8:(0)

上面的结果应该是3 ,但是结果却是4。

暂时不知该怎么解决,再说吧。

你可能感兴趣的:(HDU,树形DP)