POJ-1463 Strategic game 树形dp
题目
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]。则状态转移方程如下:
d
p
[
i
]
[
0
]
=
∑
d
p
[
j
]
[
1
]
,
j
∈
s
o
n
[
i
]
dp[i][0]=\sum dp[j][1] ,j \in son[i]
dp[i][0]=∑dp[j][1],j∈son[i]
d
p
[
i
]
[
1
]
=
∑
m
i
n
(
d
p
[
j
]
[
1
]
,
d
p
[
j
]
[
0
]
)
,
j
∈
s
o
n
[
i
]
dp[i][1]=\sum min(dp[j][1],dp[j][0]), j \in son[i]
dp[i][1]=∑min(dp[j][1],dp[j][0]),j∈son[i]
这样子一来就很清晰了,只要递归求解每个节点的值,最后输出min(dp[rt][0],dp[rt][1])就可以了
上代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 1500+5
int sn[maxn][11],fa[maxn],sn_cnt[maxn],dp[maxn][2];
void init()
{
memset(sn_cnt,0,sizeof(sn_cnt));
memset(sn,0,sizeof(sn));
memset(fa,-1,sizeof(fa));
memset(dp,0,sizeof(dp));
for(int i=0;i<maxn;i++) dp[i][1]=1;
}
void recur(int dex)
{
if(!sn_cnt[dex]) return;
for(int i=0;i<sn_cnt[dex];i++){
recur(sn[dex][i]);
dp[dex][0]+=dp[sn[dex][i]][1];
dp[dex][1]+=min(dp[sn[dex][i]][0],dp[sn[dex][i]][1]);
}
}
int main()
{
int n,dex,s,cnt,rt;
while(scanf("%d",&n)!=EOF){
init();
for(int i=1;i<=n;i++){
scanf("%d:(%d)",&dex,&cnt);
sn_cnt[dex]=cnt;
for(int j=0;j<cnt;j++)
scanf("%d",&sn[dex][j]),fa[sn[dex][j]]=dex;
}
for(int i=0;i<n;i++)
if(fa[i]==-1) rt=i;
recur(rt);
printf("%d\n",min(dp[rt][0],dp[rt][1]));
}
}