Strategic Game - HDU 1054 树形dp

来源:互联网 发布:ubuntu 14.04.4 iso 编辑:程序博客网 时间:2024/04/30 08:19

Strategic Game

Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4762    Accepted Submission(s): 2158


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
40:(1) 11:(2) 2 32:(0)3:(0)53:(3) 1 4 21:(1) 02:(0)0:(0)4:(0)
 

Sample Output
12

题意:每个点都可以站人或不站人,使得每个边至少有一端有人,问你最少需要多少人。

思路:用dp[i][0]代表i点不站人时需要的最小人数,此时他的子节点都必须站人,dp[i][1]表示i点站人时需要的最小人数,此时他的子节点都可以站人也可以不站人。

AC代码如下:

#include<cstdio>#include<cstring>#include<vector>#include<algorithm>using namespace std;vector<int > vc[1510];int dp[1510][2],vis[1510];void dfs(int a){ int i,j,k;  dp[a][0]=0;dp[a][1]=1;  vis[a]=1;  for(i=0;i<vc[a].size();i++)  { k=vc[a][i];    if(vis[k])     continue;    dfs(k);    dp[a][0]+=dp[k][1];    dp[a][1]+=min(dp[k][0],dp[k][1]);  }}int main(){ int n,m,i,j,k,u,v,ans;  while(~scanf("%d",&n))  { memset(dp,0,sizeof(dp));    memset(vis,0,sizeof(vis));    for(i=1;i<=n;i++)     vc[i].clear();    for(i=1;i<=n;i++)    { scanf("%d:(%d)",&u,&m);      for(j=1;j<=m;j++)      { scanf("%d",&v);        vc[u].push_back(v);        vc[v].push_back(u);      }    }    dfs(0);    ans=min(dp[0][0],dp[0][1]);    printf("%d\n",ans);  }}


0 0