程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> hdu1054Strategic Game(樹形DP)

hdu1054Strategic Game(樹形DP)

編輯:C++入門知識

Problem 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.

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:

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解題:在一棵樹上的每一個點,只存在放與不放兩種情況,那麼當根不放時,則根的孩子節點是必須放的情況,如果根不放時,則根的孩子可以放也可以不放。	公式: dp[p][0]+=dp[child][1];  dp[p][1]=min(dp[p][1]+dp[child][0],dp[p][1]+dp[child][1]);  p:根節點   child:p的子節點
#include
#include
#define inf 99999
struct nnn
{
    int k;
    int son[1505];
}node[1505];
int dp[1505][2],vist[1505],n;
int min(int a,int b)
{
    return a>b?b:a;
}
void dfs(int p)
{
    dp[p][0]=0;dp[p][1]=1; vist[p]=1;
    for(int k=1;k<=node[p].k;k++)
    {
        int child=node[p].son[k];
        if(vist[child])continue;//區分根節點與子節點,這樣不會形成循環
        dfs(child);
        dp[p][0]+=dp[child][1];
        dp[p][1]=min(dp[p][1]+dp[child][0],dp[p][1]+dp[child][1]);
    }
}
int main()
{
    int p,num,child,sum;
    while(scanf("%d",&n)==1)
    {
        memset(vist,0,sizeof(vist));
        for(int i=0;idp[0][1]) 
        sum=dp[0][1];
        printf("%d\n",sum);
    }
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved