题源:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=20437#problem/E
E - 树形DP一
Time Limit:2000MS Memory Limit:10000KB 64bit IO Format:%I64d & %I64uSubmit Status
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.
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[i][0]和DP[i][1]分别表示第i个节点没有士兵和第i个节点有士兵,获得的总的最小士兵数。
则状态转移方程为:
DP[i][1] += DP[j][0],
DP[i][0] += min{DP[j][0],DP[j][1]};其中j为i的孩子节点。
参考博客http://hi.baidu.com/wang_125309/item/5434999f82cd01bbcc80e56a
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
const int maxn=1510;
int map[maxn][maxn];
int son[maxn];
int father[maxn];
int dp[maxn][2];//0,不选,1,选
int n,res;
int min(int a,int b)
{
return a<b? a:b;
}
void dfs(int u)
{
int ok=0;
for(int i=0;i<son[u];i++)
{
int k=map[u][i];
//printf("i=%d,k=%d\n",u,k);
dfs(k);
dp[u][0]+=dp[k][1];
dp[u][1]+=min(dp[k][0],dp[k][1]);
if(!ok)
{
dp[u][1]++;
ok=1;
}
//printf("dp[%d][0]=%d,dp[%d][1]=%d\n",u,dp[u][0],u,dp[u][1]);
}
}
void DP()
{
int i;
memset(dp,0,sizeof(dp));
for(i=0;i<n;i++)
if(son[i]==0)
{
dp[i][1]=1;
dp[i][0]=0;
//printf("i=%d\n",i);
}
for(i=0;i<n;i++)
if(father[i]==0)
{
dfs(i);
res=i;
//printf("res=%d\n",res);
break;
}
}
int main()
{
int i,j,u,d,v;
while(scanf("%d",&n)!=EOF)
{
memset(son,0,sizeof(son));
memset(map,0,sizeof(map));
memset(father,0,sizeof(father));
for(i=0;i<n;i++)
{
scanf("%d:(%d)",&u,&d);
for(j=0;j<d;j++)
{scanf("%d",&v);
map[u][son[u]++]=v;
father[v]++;
}
}
DP();
printf("%d\n",min(dp[res][0],dp[res][1]));
}
//system("pause");
return 0;
}