您的位置:首页 > 其它

hdu1054 树形dp&&二分图

2016-03-24 21:08 183 查看
B - Strategic Game
Time Limit:10000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit Status Practice HDU 1054

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:

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
前几天刚做过这题,二分图A的,树形dp同样可以解决
注意 此题要求任意一条路径上都应当有人看守,所有dp[root][0]+=dp[k][1],,,此处0的时候只能选着儿子节点的1

dp[root][1]=min(dp[k][0],dp[k][1])
题很水不多说了

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1505;
struct node{
int to,net;
}edge[maxn<<1];

int head[maxn];
bool  vis[maxn];
int dp[maxn][2];
int tot;

void addedge(int u,int v){

edge[tot].to=v;
edge[tot].net=head[u];
head[u]=tot++;

edge[tot].to=u;
edge[tot].net=head[v];
head[v]=tot++;

}

void dfs(int root){
vis[root]=true;

for(int i=head[root];i!=-1;i=edge[i].net){
int v=edge[i].to;
if(!vis[v]){
dfs(v);
dp[root][0]+=dp[v][1];
dp[root][1]+=min(dp[v][1],dp[v][0]);

}
}
}

int main(){
int t;
while(scanf("%d",&t)!=EOF){
memset(dp,0,sizeof(dp));
memset(vis,false,sizeof(vis));
tot=0;
memset(head,-1,sizeof(head));
for(int i=1;i<=t;i++){
int n,x,y;
scanf("%d:(%d)",&x,&n);
for(int j=1;j<=n;j++){
scanf("%d",&y);
addedge(x,y);
}
}
int root=0;
for(int i=0;i<t;i++)
dp[i][1]=1;
dfs(root);
int ans=min(dp[root][0],dp[root][1]);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: