zoukankan      html  css  js  c++  java
  • Strategic Game

    描述

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

    输入

    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.

    输出

    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:

    样例输入

    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)

    样例输出

    1
    2

    解题思路:树形dp,dp[i][j]表示在第i个位置,j表示是否放置。

    #include <bits/stdc++.h>
    using namespace std;
    #define LL long long
    const int N=1550;
    vector<int>G[N];
    int d[N],dp[N][2];
    void dfs(int u)
    {
        dp[u][1]=1;
        for(int i=0;i<G[u].size();i++){
            int v=G[u][i];
            dfs(v);
            dp[u][1]+=min(dp[v][0],dp[v][1]);
            dp[u][0]+=dp[v][1];
        }
    
    }
    int main()
    {    
        int  n,m,u,v;
        while(scanf("%d",&n)!=EOF){
            for(int i=0;i<=n;i++) G[i].clear(),d[i]=dp[i][0]=dp[i][1]=0;
            for(int i=1;i<=n;i++){
                scanf("%d:(%d)",&u,&m);
                for(int j=1;j<=m;j++){
                    scanf("%d",&v);
                    G[u].push_back(v);
                    d[v]++;
                }
            }
            int rt=-1;
            for(int i=0;i<n;i++) if(d[i]==0) rt=i;
            dfs(rt);
            printf("%d
    ",min(dp[rt][0],dp[rt][1]));
        }
    }
  • 相关阅读:
    python中创建实例属性
    Python中if __name__ == "__main__": 的理解
    模块
    python函数式编程
    python-复杂生成式
    生成器的测试
    mysql乱码配置
    javascript
    Sql Server 2008 R2 下载地址
    Microsoft Data Access Components 2.8
  • 原文地址:https://www.cnblogs.com/ww123/p/11752637.html
Copyright © 2011-2022 走看看