hdu1054-树形dp

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1054

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:

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:

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)

Output
1
2

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

题意
给出n个点组成的树,在一个节点放置士兵可以监视与该节点相连的所有路径,问监视所有路最少需要几个士兵。

思路
有点裸的树形dp,dp[i][1]表示以i为根节点的子树,在i节点放置士兵时的最小值,dp[i][0]表示以i为根节点的子树,在i节点不放置士兵时的最小值。设j为i的一个子节点,可以推出dp[i][0]+=dp[j][1],dp[i][1]+=min(dp[j][1],dp[j][0])。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const int maxn = 3600;
struct node {
int s, e, next;
}edge[maxn];
int head[maxn], dp[maxn][2], vis[maxn];
int len;
int n;
void add(int s, int e) {
edge[len].s = s;
edge[len].e = e;
edge[len].next = head[s];
head[s] = len++;

}
void dfs(int x) {
vis[x] = 1;
dp[x][1] = 1;
dp[x][0] = 0;
for (int i = head[x]; i != -1; i = edge[i].next) {
int t = edge[i].e;
if (vis[t])
continue;
dfs(t);
dp[x][0] += dp[t][1];
dp[x][1] += min(dp[t][1], dp[t][0]);
}
}
int main() {
while (cin >> n) {
int x, y, t;
memset(head, -1, sizeof(head));
memset(vis, 0, sizeof(vis));
len = 0;
for (int i = 0; i < n; i++) {
scanf("%d:(%d)", &x, &t);
x++;
while (t--) {
scanf("%d", &y);
y++;
add(x, y);
add(y, x);
}
}
dfs(1);
printf("%d\n", min(dp[1][0], dp[1][1]));
}
}

谢谢你请我吃糖果

你可能感兴趣的:(hdu1054-树形dp)