POJ1463-Strategic game

来源:互联网 发布:网络品牌策划 编辑:程序博客网 时间:2024/05/16 17:12

Strategic game

Time Limit: 2000MS Memory Limit: 10000K
Total Submissions: 8433 Accepted: 3945
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

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
Source

Southeastern Europe 2000

题目大意: 给出一个树,在一些结点放士兵,要监视所有点边,问最少放多少士兵。
解题思路:树形dp,
dp[i][0]=dp[j1][1]+dp[j2][1]+...dp[jk][1]ji的孩子
dp[i][1]=1+min(dp[j1][1],dp[j1][0])+min(dp[j2][1],dp[j2][0])+...+min(dp[jk][1],dp[jk][0])ji的孩子
对于叶子结点,dp[i][1]=1,dp[i][0]=0

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespace std;const int MAXN=1e5+5;int head[MAXN],tot;int dp[MAXN][2];struct Edge{    int from,to,nxt;}e[MAXN*2];void addedge(int u,int v){    e[tot].from=u;    e[tot].to=v;    e[tot].nxt=head[u];    head[u]=tot++;}void dfs(int rt,int fa){    dp[rt][0]=0;dp[rt][1]=1;    for(int i=head[rt];i!=-1;i=e[i].nxt)    {        int to=e[i].to;        if(to==fa) return;        dfs(to,rt);        dp[rt][0]+=dp[to][1];        dp[rt][1]+=min(dp[to][0],dp[to][1]);    }}int main(){    int n;    while(scanf("%d",&n)!=EOF)    {        tot=0;        memset(head,-1,sizeof(head));        memset(dp,0,sizeof(dp));        int root=-1;        for(int i=1;i<=n;++i)        {            int u,v,m;            scanf("%d:(%d)",&u,&m);            if(root==-1&&m!=0) root=u;            for(int j=1;j<=m;++j)            {                scanf("%d",&v);                addedge(u,v);                addedge(v,u);            }        }        dfs(root,-1);        printf("%d\n",min(dp[root][1],dp[root][0]));    }    return 0;}
阅读全文
0 0
原创粉丝点击