您的位置:首页 > 其它

hdu1054 Strategic Game(树形dp)

2018-01-18 11:43 429 查看

Strategic Game

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


[align=left]Problem Description[/align]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:
 
[align=left]Sample Input[/align]
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) 
[align=left]Sample Output[/align]
1
2 题意:给出一棵树,每个点可以监视它本身和与他相邻的点,问最小选择多少个点,可以将整棵树都监视
这题有很多种解法,可以用二部图匹配写,也可以用网络流写,由于是在树形dp专题里遇到的,所以就用树形dp
这和树形dp的入门题,hdu1520十分相似,同样是每个点两种状态,取和不取
分别用1,0标记取与不取,可得状态转移方程
dp[fa][1]+=min(dp[son][1],dp[son][0])
dp[fa][0]+=dp[son][1]
然后由根递归到叶,回溯时更新状态即可
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<math.h>
#include<vector>
#define mem(a,b) memset(a,b,sizeof(
d3a9
a))
using namespace std;
const int N=1510;
int a
,dp
[2],f
;
vector<int>e
;
void dfs(int u)
{
dp[u][1]=1;
for(int i=0;i<e[u].size();i++)
{
int v=e[u][i];
dfs(v);
dp[u][1]+=min(dp[v][1],dp[v][0]);
dp[u][0]+=dp[v][1];
}
}
int main()
{
int n,u,v,root,m;
while(~scanf("%d",&n))
{
mem(dp,0);
mem(f,-1);
for(int i=0;i<n;i++)
e[i].clear();
for(int i=1;i<=n;i++)
{
scanf("%d:(%d)",&u,&m);
a[u]=m;
while(m--)
{
scanf("%d",&v);
e[u].push_back(v);
f[v]=u;
root=v;
}
}
while(f[root]!=-1)root=f[root];
dfs(root);
printf("%d\n",min(dp[root][0],dp[root][1]));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: