Strategic game(POJ 1463 树形DP)

Strategic game
Time Limit: 2000MS   Memory Limit: 10000K
Total Submissions: 7490   Accepted: 3483

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: 
Strategic game(POJ 1463 树形DP)
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 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

一道简单的树形DP,状态转移方程:和上一次做的题目基本一样
  dp[node][0]+=dp[tree[node][i]][1];

  dp[node][1]+=min(dp[tree[node][i]][0],dp[tree[node][i]][1]);  然后+1

一开始写成 dp[node][1]+=dp[tree[node][i]][0];

 #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
#define Max 1506
int dp[Max][],fa[Max],tree[Max][];
int n;
int num[Max];
void tree_dp(int node)
{
int i;
for(i=;i<num[node];i++)
{
tree_dp(tree[node][i]);
dp[node][]+=dp[tree[node][i]][];
dp[node][]+=min(dp[tree[node][i]][],dp[tree[node][i]][]);
}
dp[node][]++;
return;
}
int main()
{
int i,j;
int a,b;
int k,root,f;
freopen("in.txt","r",stdin);
while(scanf("%d",&n)!=EOF)
{
memset(dp,,sizeof(dp));
memset(tree,,sizeof(tree));
for(i=;i<Max;i++)
fa[i]=-;
for(i=;i<n;i++)
{
scanf("%d%*c%*c%d%*c",&f,&k);
num[f]=k;
for(j=;j<k;j++)
{
scanf("%d",&tree[f][j]);
fa[tree[f][j]]=f;
}
}
root=;
while(fa[root]!=-)
root=fa[root];
tree_dp(root);
printf("%d\n",min(dp[root][],dp[root][]));
}
return ;
}
上一篇:poj 1463(树形dp)


下一篇:29、Jquery Ajax