POJ 1463 && HDU 1054 Strategic Game(树形DP)
来源:互联网 发布:剑三成男眼睛数据 编辑:程序博客网 时间:2024/04/30 08:35
Description
给出一棵树,要求找到最少放几个士兵才能将所有点都看守到,每个节点的士兵只能看守临近一个的节点
Input
多组用例,每组用例第一行为节点数n,之后n行第i行输入第i-1个节点临近的节点,括号中的数表示临近的节点数m,之后m个数表示临近的节点下标,以文件尾结束输入
Output
对于每组用例,输出放置的最少士兵数
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,因为是无向图所以建边时两边都要建,用dp[i][0]表示i节点没有放士兵时的最少士兵数,dp[i][1]表示i节点放士兵的最少士兵数,则有
dp[fa[i]][0]+=dp[i][1]
dp[fa[i]][1]+=min(dp[i][0],dp[i][1])
答案即为min(dp[root][0],dp[root][1])(root为根节点)
Code
#include<cstdio>#include<iostream>#include<cstring>using namespace std;#define maxn 1555struct node{ int to; int next;}edge[2*maxn];int tol,root;int head[maxn];int dp[maxn][2];int vis[maxn];void init()//初始化 { tol=0; root=-1; memset(head,-1,sizeof(head)); memset(dp,0,sizeof(dp)); memset(vis,0,sizeof(vis));}void add(int a,int b)//建双向边 { edge[tol].to=b; edge[tol].next=head[a]; head[a]=tol++; edge[tol].to=a; edge[tol].next=head[b]; head[b]=tol++;}void dfs(int u){ vis[u]=1;//标记 dp[u][0]=0;//该点不放置士兵则最少士兵数就为0 dp[u][1]=1;//该点放置士兵则最少士兵数就为1 for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].to; if(!vis[v])//这个子节点还未被访问 { dfs(v); dp[u][0]+=dp[v][1];//该点不放士兵 dp[u][1]+=min(dp[v][0],dp[v][1]);//该点放士兵 } }}int main(){ int n; while(~scanf("%d",&n)) { init();//初始化 int a,b,m; for(int i=1;i<=n;i++) { scanf("%d:(%d)",&a,&m); if(root==-1)//找到根节点 root=a; for(int j=0;j<m;j++) { scanf("%d",&b); add(a,b); } } dfs(root); printf("%d\n",min(dp[root][0],dp[root][1])); } return 0;}
0 0
- POJ 1463 && HDU 1054 Strategic Game(树形DP)
- 【POJ 1463】【hdu 1054】Strategic game(树形dp)
- POJ 1463 && HDU 1054 Strategic Game (树形DP)
- hdu 1054 &&poj 1463 Strategic Game(树形dp)
- poj 1463 Strategic game (树形DP)
- hdu - 1054 - Strategic Game(树形dp)
- HDU 1054 Strategic Game (树形DP)
- 树形DP专辑--POJ 1463 Strategic game
- poj 1463 Strategic game(树形DP)
- POJ 1463 Strategic game( 树形DP )
- POJ 1463-Strategic game(树形DP)
- POJ - 1463Strategic game入门树形DP
- poj 1463 Strategic game 树形dp
- poj 1463Strategic game【树形dp】
- poj 1463 Strategic game(树形dp)
- poj 1463 Strategic game 树形dp
- poj 1463 Strategic game 树形dp
- POJ Strategic game(树形DP)
- Xcode 编译错误 之 redefinition of ‘...’
- JavaWeb学习之Filter
- Windows10 如何会成为微软的新起点?
- Windows10 如何会成为微软的新起点?
- 带大家一步一步封装一个聊天键盘(二)
- POJ 1463 && HDU 1054 Strategic Game(树形DP)
- OSI七层模型详解
- java单利模式
- Windows10 如何会成为微软的新起点?
- CheckBox也可以进行单选
- WebSphere集群环境修改IHS端口号的方法
- INFA Linux 环境配置
- Windows10 如何会成为微软的新起点?
- 缩放动画