Strategic game
Time Limit: 2000MS | Memory Limit: 10000K | |
Total Submissions: 5498 | Accepted: 2484 |
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).
Your program should find the minimum number of soldiers that Bob has to put for a given tree.
For example for the tree:
![](http://poj.org/images/1463_1.jpg)
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 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.
- 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
Source
本来感觉很简单的一个题,没想到竟然做了几个小时,又是初始化的问题,这次不是vector却是vis[],想哭的感觉。。。
#include <iostream> #include<vector> #include<stdio.h> using namespace std; vector<int>s[1600]; int dp[2][1600],vis[1600],minn,f[1600]; int min(int i,int j) { return i<j?i:j; } void dfs(int i) { dp[0][i]=0; dp[1][i]=1; int j; if(s[i].size()==0) return ; for(j=0;j<s[i].size();j++) { if(vis[s[i][j]]==0)//WA多次后,有一次直接把这个标记的去掉竟然AC了,回过头来又检查发现是vis[]没初始化,修改之后再次提交发现时间没减少多少,我想可能是因为我从树的顶点开始dp { dfs(s[i][j]); vis[s[i][j]]=1; } dp[0][i]+=dp[1][s[i][j]];//0表示无哨兵,i处无哨兵则s[i][j]处必须有哨兵 dp[1][i]+=min(dp[0][s[i][j]],dp[1][s[i][j]]);//1表示有哨兵,i处有哨兵的情况等于s[i][j]处有哨兵或者无哨兵的最小值 } } int main() { int i,j,n,m,a,b,k,sum,leve; while(scanf("%d",&n)!=EOF) { for(i=0;i<n;i++) { vis[i]=0; s[i].clear(); } for(i=0;i<=n;i++) f[i]=i; leve=0; sum=0; for(i=0;i<n;i++) { scanf("%d:(%d)",&a,&m); sum+=a;//所有节点算总和 for(j=0;j<m;j++) { cin>>b; s[a].push_back(b); leve+=b;//算所有子树总和 } } k=sum-leve;//二者做差便是根节点 dfs(k); minn=min(dp[0][k],dp[1][k]);//两种情况的最小值 cout <<minn<< endl; } return 0; }