POJ 1463-Strategic game(树形DP)

来源:互联网 发布:java中mkdir 编辑:程序博客网 时间:2024/04/30 07:13

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:

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

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,虽说是照着代码敲出来的==||。。

CODE:

#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>#include <string>#include <cstring>#include <queue>#include <stack>#include <vector>#include <set>#include <map>const int inf=0xfffffff;typedef long long ll;using namespace std;int cnt[1505], pre[1505], n, root;int dp[1505][2];void DP(int root){    int dp0 = 0, dp1 = 0;    if(cnt[root] == 0){        dp[root][1] = 1;        dp[root][0] = 0;        return;    }    for(int i = 0; i < n; ++i){        if(pre[i] == root){            DP(i);            dp1 += min(dp[i][1], dp[i][0]);            dp0 += dp[i][1];        }    }    dp[root][1] = dp1 + 1;    dp[root][0] = dp0;}int main(){    //freopen("in", "r", stdin);    int f, s;    while(~scanf("%d", &n)){        memset(dp, 0, sizeof(dp));        memset(pre, -1, sizeof(pre));        memset(cnt, -1, sizeof(cnt));        root = -1;        int num;        for(int i = 0; i < n; ++i){            scanf("%d: (%d)", &f, &num);            cnt[f] = num;            if(root == -1) root = f;            while(num--){                scanf("%d", &s);                pre[s] = f;                if(s == root) root = f;            }        }        DP(root);        printf("%d\n", min(dp[root][0], dp[root][1]));    }    return 0;}


0 0
原创粉丝点击