您的位置:首页 > 其它

hdu 1054 &&poj 1463 Strategic Game(树形dp)

2015-12-23 16:52 501 查看
Strategic Game

时间限制1秒 内存限制10240KB

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 theminimum
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 setrepresents 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 dataset, print one integer number in a single line that gives the result (theminimum 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

solution:

给出有向图,要求找出用最少的人数可以看守所有的边。

dp[i][0] 以i为根的子树,i上不放人时,需要的最少人数。

dp[i][1] 以i为根的子树,i上放人时,需要的最少人数。

状态转移方程:j为i的儿子节点

dp[i][0] += dp[j][1] ;

dp[i][1] += min( dp[j][0],dp[j][1] ) ;

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#define maxn 1550
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
using namespace std;
int dp[maxn][2], vis[maxn];
int head[maxn], e;
int n;
struct node{
int to, next;
}edge[maxn * 2];
void init()
{
e = 0;
mem0(vis); mem0(dp);
mem1(head);
}
void add(int u, int v)
{
edge[e].to = v;
edge[e].next = head[u];
head[u] = e++;
}
void dfs(int root)
{
vis[root] = 1;
for (int i = head[root]; i != -1; i = edge[i].next)
{
int son = edge[i].to;
if (vis[son] == 0)
{
dfs(son);
dp[root][0] += dp[son][1];
dp[root][1] += min(dp[son][1], dp[son][0]);
}
}
dp[root][1] += 1;
}
int main()
{
int i, j, root, t, x, y;
while (scanf("%d", &n) != EOF)
{
init();
for (j = 1; j <= n; j++)
{
scanf("%d:(%d)", &x, &t);
if (j == 1)root = x;
for (i = 0; i<t; i++)
{
scanf("%d", &y);
add(x, y);
add(y, x);
}
}
dfs(root);
printf("%d\n", min(dp[root][0], dp[root][1]));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: