天天看點

poj1463(簡單樹形dp)

Strategic game

Time Limit: 2000MS Memory Limit: 10000K
Total Submissions: 9313 Accepted: 4368

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:

poj1463(簡單樹形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      

一句話題意:如果一個點上放士兵,那士兵相鄰位置的路都會被看守住,現在問如果要把所有路都看守住,至少需要放多少士兵。

設dp[x][1],表示x放士兵,dp[x][0]表示x不放士兵

那麼dp[x][1]+=min(dp[son][0],dp[son][1])

dp[x][0]+=dp[x][1];

。。。。。。。。。。。。。還有,記住找根,不是是以的點,都可以當根

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct my{
       int next;
       int v;
};

const int maxn=3000+10;
int adj[maxn],fa,dp[maxn][3],du[maxn];
my bian[maxn];

void myinsert(int u,int v){
     bian[++fa].v=v;
     bian[fa].next=adj[u];
     adj[u]=fa;
}

void dfs(int x){
     if(adj[x]==-1) {
        dp[x][1]=1;
        dp[x][0]=0;
        return ;
     }
     for (int i=adj[x];i!=-1;i=bian[i].next){
        int v=bian[i].v;
        dfs(v);
        dp[x][0]+=dp[v][1];
        dp[x][1]+=min(dp[v][1],dp[v][0]);
     }
}

int main(){
    int n,u,v,m;
    while(scanf("%d",&n)!=EOF){
    memset(adj,-1,sizeof(adj));
    memset(bian,-1,sizeof(bian));
    memset(dp,0,sizeof(dp));
    memset(du,0,sizeof(du));
    fa=0;
    for (int k=1;k<=n;k++){
        scanf("%d",&u);
        dp[u][1]=1;
        scanf(":(%d)",&m);
        for (int i=1;i<=m;i++){
            scanf("%d",&v);
            myinsert(u,v);
            du[v]++;
        }
      }
      int root=0;
      for (int i=0;i<n;i++){
        if(du[i]==0) {root=i;break;}
      }
      dfs(root);
      printf("%d\n",min(dp[root][0],dp[root][1]));
    }
return 0;
}      

轉載于:https://www.cnblogs.com/lmjer/p/9419177.html