1. 程式人生 > >Strategic game (樹形DP)

Strategic game (樹形DP)

Strategic game

 POJ - 1463

Bo b 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).

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
題意:N個數n-1條邊,代表N-1條路,每條路至少需要一個警衛看管,問每條路都至少有一個警衛看管最少需要安排幾個警衛。
思路:
  和POJ - 3342 基本上一模一樣。樹形DP模板題,dp[x][0]表示在不選x這個節點上不放置警衛時以x為根節點的子樹最少需要設定的警衛數。dp[x][1]表示選x這個節點上不放置警衛時以x為根節點的子樹最少需要設定的警衛數。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=5000;
vector<int>v[maxn];
int n;
int in[maxn];
int vis[maxn];
int dp[maxn][2];
void dfs(int x)
{

        dp[x][1]=1;
        dp[x][0]=0;
        vis[x]=1;
    for(int i=0;i<v[x].size();i++)
    {
        if(vis[v[x][i]])
            continue;
        int to=v[x][i];
        dfs(to);
        dp[x][1]+=min(dp[to][0],dp[to][1]);
        dp[x][0]+=dp[to][1];
    }
}
int main()
{
    while(~scanf("%d",&n))
    {
        memset(vis,0,sizeof(vis));
        memset(in,0,sizeof(in));
        memset(dp,0,sizeof(dp));
        for(int i=0;i<=n;i++)
            v[i].clear();
        int f,sum,child;
        for(int i=0;i<n;i++)
        {
            scanf("%d:(%d)",&f,&sum);
            while(sum--)
            {
                scanf("%d",&child);
                v[f].push_back(child);
                in[child]++;
            } 
        }
        for(int i=0;i<n;i++)
        {
            if(in[i]==0)
            {
                dfs(i);
                printf("%d\n",min(dp[i][1],dp[i][0]));
                break;
            }
        }
    }
}