http://poj.org/problem?id=1463

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. 

For example for the tree: 


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

Input

The input 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_identifiernumber_of_roads 
    or 
    node_identifier:(0) 


The node identifiers are integer numbers between 0 and n-1, for n nodes (0 < n <= 1500);the number_of_roads in each line of input will no more than 10. Every edge appears only once in the input data.

Output

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:

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,dp[u][0]表示结点u不选,dp[u][1]表示结点u选,如果不选,那么子结点必须选,如果已选子节点就可选可不选,状态转移方程为

dp[u][0] += dp[v][1]; dp[u][1] += min(dp[v][0], dp[v][1]);

#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> G[1505];
bool vis[1505],isroot[1505];
int dp[1505][2];
bool dfs(int x){
	vis[x]=true;
	dp[x][0]=0;
	dp[x][1]=1;
	for(int i=0;i<G[x].size();i++){
		int t=G[x][i];
		if(!vis[t]){
			dfs(t);
			dp[x][0]+=dp[t][1];
			dp[x][1]+=min(dp[t][0],dp[t][1]);
		}
	}
}
int main(){
	int n;
	while(~scanf("%d",&n)){
		for(int i=0;i<n;i++){
			G[i].clear();
			isroot[i]=true;
		}
		
		memset(vis,0,sizeof(vis));
		int u,v,m;
		for(int i=0;i<n;i++){
			scanf("%d:(%d)",&u,&m);
			while(m--){
				scanf("%d",&v);
				G[u].push_back(v);
			    isroot[v]=false;
			}
		}
		int root;
		for(int i=0;i<n;i++){
			if(isroot[i]){
				root=i;
				break;
			}
		}
		dfs(root);
		int ans=min(dp[root][0],dp[root][1]);
		printf("%d\n",ans);
	}
	return 0;
}