2012-05-31 08:11:28Morris
[ACM-ICPC][樹形DP] 2038 - Strategic game
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 file contains several data sets in text format. Each data set represents a tree with the following description: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.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)
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).
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[][0] 不擺放, 則 dp[][0] += dp[所有子節點][1]
dp[][1] 擺放, 則 dp[][1] += dp[所有子節點的]min([0], [1]);
最後 dp[][1] += 1;
#include <stdio.h>
#include <vector>
#define min(x, y) ((x) < (y) ? (x) : (y))
using namespace std;
struct Arc {
int to;
};
vector<Arc> nd[2000];
int dp[2000][2], used[2000];
int dfs(int node) {
used[node] = 1;
dp[node][0] = 0;
dp[node][1] = 1;
for(vector<Arc>::iterator i = nd[node].begin(); i != nd[node].end(); i++) {
if(used[i->to] == 0) {
dfs(i->to);
dp[node][0] += dp[i->to][1];
dp[node][1] += min(dp[i->to][0], dp[i->to][1]);
}
}
return min(dp[node][0], dp[node][1]);
}
int main() {
int n, m, st, ed, i;
while(scanf("%d", &n) == 1) {
for(i = 0; i < n; i++)
nd[i].clear(), used[i] = 0;
Arc tmp;
for(i = 0; i < n; i++) {
scanf("%d: (%d)", &st, &m);
while(m--) {
scanf("%d", &ed);
tmp.to = ed;
nd[st].push_back(tmp);
tmp.to = st;
nd[ed].push_back(tmp);
}
}
printf("%d\n", dfs(0));
}
return 0;
}