Strategic game
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的开端
1. 状态: dp[u][0]: 表示选取节点u作为放哨点时, 需要最少的节点数.
dp[u][1]: 表示不选取节点u作为放哨点时, 需要最少的节点数.
2. 状态转移方程:
当u是叶子节点时; dp[u][0] = 0; dp[u][1] = 1;
否则: u是起点, v是末点. 边: u->v
dp[u][0] += dp[v][1];
dp[u][1] += min(dp[v][0],dp[v][1]);
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 1502
struct node
{
int u, v;
int next;
}edges[MAX*2];
int n, num;
int sum1, sum2;
int root;
int first[MAX];
int dp[MAX][2];
int child[MAX];
inline void add(int u,int v)
{
edges[num].u = u;
edges[num].v = v;
edges[num].next = first[u];
first[u] = num++;
}
inline int min(int a,int b)
{
return a < b ? a : b;
}
void read_graph()
{
memset(first,-1,sizeof(first));
memset(edges,0,sizeof(edges));
int u, v, m;
sum1 = sum2 = 0;
num = 0;
for(int i = 0; i < n; ++i)
{
scanf("%d:(%d)",&u,&m);
sum1 += u;
child[u] = m;
for(int j = 0; j < m; ++j)
{
scanf("%d",&v);
sum2 += v;
add(u,v);
}
}
root = sum1 - sum2;
}
void solve(int u)
{
dp[u][0] = 0;
dp[u][1] = 1;
if(child[u] == 0) return ;
for(int e = first[u]; e != -1; e = edges[e].next)
{
int v = edges[e].v;
solve(v);
dp[u][0] += dp[v][1];
dp[u][1] += min(dp[v][0],dp[v][1]);
}
}
int main()
{
// freopen("input.txt","r",stdin);
while(scanf("%d",&n) != EOF)
{
read_graph();
memset(dp,0,sizeof(dp));
solve(root);
printf("%d\n",min(dp[root][0],dp[root][1]));
}
return 0;
}