您的位置:首页 > 其它

hdu 1054 Strategic Game 经典树形DP

2013-10-28 23:11 302 查看

Strategic Game

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

[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

[align=left]Source[/align]
Southeastern Europe 2000

这一道题和 hdu2412是一个类型的。而且还容易了一些。
/article/6680143.html

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct node
{
int next[1502];
int num;
}f[1502];
int dp[1502][2];

int Min(int x,int y)
{
return x>y? y:x;
}

void dfs(int k)
{
int i,j,cur;
if( f[k].num==0 )
{
dp[k][0]=0;
dp[k][1]=1;
return;
}
for(i=1;i<=f[k].num;i++)
{
cur=f[k].next[i];
dfs(cur);
j=Min(dp[cur][0],dp[cur][1]);
dp[k][1]+=j;

dp[k][0]+=dp[cur][1];
}
dp[k][1]++;
}

int main()
{
int n,root,r,num,x,len;
int i,j;
while(scanf("%d",&n)>0)
{
getchar();
for(i=1;i<=1500;i++)  f[i].num=0;
for(i=1;i<=n;i++)
{
scanf("%d:(%d)",&r,&num);
if(i==1) root=r;
f[r].num=num;
len=0;
for(j=1;j<=num;j++)
{
scanf("%d",&x);
f[r].next[++len]=x;
}
}
memset(dp,0,sizeof(dp));
dfs(root);
printf("%d\n",Min(dp[root][0],dp[root][1]));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: