Strategic Game
Time Limit: 20000/10000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10312 Accepted Submission(s): 4825
Problem 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:
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][1/0]表示以i为根节点放士兵和不放士兵的最小值
如果父亲结点没放哨兵,那么子结点肯定要放置哨兵;
如果父亲放置了哨兵,那么子结点可以考虑放或者不放。
所以很容易写出状态转移方程 dp[root][1] += min(dp[v][1],dp[v][0]); dp[root][0] += dp[v][1]
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <iomanip>
#define ll long long
#define inf 0x3f3f3f3f
#define Max 2002
using namespace std;
vector <int > edge[Max];
int n,u,v,w;
int dp[Max][2];
//dp[i][1/0]表示以i为根节点放士兵和不放士兵的最小值
void dfs(int root,int fa)
{
dp[root][1]=1;
dp[root][0]=0;
for(int i=0;i<edge[root].size();i++)
{
int v=edge[root][i];
if(v==fa) continue;
dfs(v,root);
dp[root][0]+=dp[v][1];//父节点没有放,子节点一定要放
dp[root][1]+=min(dp[v][0],dp[v][1]);//父节点放了,子节点可放可不放
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(dp,0,sizeof(dp));
for(int i=0;i<=n;i++)
edge[i].clear();
for(int i=0;i<n;i++)
{
scanf("%d:(%d)",&u,&w);
for(int j=0;j<w;j++)
{
scanf("%d",&v);
edge[u].push_back(v);
edge[v].push_back(u);
}
}
dfs(0,-1);
printf("%d\n",min(dp[0][0],dp[0][1]));
}
return 0;
}