hdu4714 Tree2cycle 树形DP
来源:互联网 发布:天音软件 编辑:程序博客网 时间:2024/06/11 00:07
题目是问把一棵树通过剪边、加边形成一个环的最小代价。
分成两步,先把树剪成一些链,再把链连接成一个环。
My Code:
//dp[u][0]表示u节点是所在链的端点时,以u节点为根节点的子树形成的最少的切边数。//dp[u][1]表示u节点是所在链的中间的点时,以u节点为根节点的子树形成的最少的切边数。#pragma comment(linker,"/STACK:102400000,102400000")#include <cstdio>#include <cstring>#include <queue>#include <vector>#include <algorithm>using namespace std;#define maxn 1000100#define INF 1000100vector<int> G[maxn];int dp[maxn][2];int root;void dfs(int u, int fa){ int len = G[u].size(); int sum=0,cld=0; for(int i = 0; i < len; i++) { int v=G[u][i]; if(v==fa)continue; cld++; dfs(v,u); } int min1,min2; vector<int> hehe; //存的是dp[v][0]-dp[v][1] for(int i = 0; i < len; i++) { int v=G[u][i]; if(v==fa)continue; int tmp=min(dp[v][1],dp[v][0]+1); //当v节点的[1]值不存在时,需要v的[0]状态切掉与u相连 sum+=tmp; //的那条边,所以+1 hehe.push_back(dp[v][0]-tmp); } sort(hehe.begin(), hehe.end()); if(cld==0){dp[u][0]=0;dp[u][1]=INF;return;} if(cld==1){dp[u][0]=sum+hehe[0];dp[u][1]=INF;return;} //此时dp[u][0]=dp[v][0]; min1=hehe[0];min2=hehe[1]; dp[u][0]=sum+min1; //选一个儿子与u相连,,其他断开 dp[u][1]=sum+min1+min2+1; //选两个儿子与u相连,其他断开,不过要断开u节点的祖先,所以+1}int main(){ int T;scanf("%d",&T); while(T--) { int n;scanf("%d",&n); for(int i = 0; i <= n; i++)G[i].clear(); for(int i = 0; i <= n; i++)dp[i][0]=dp[i][1]=0; for(int i = 1; i < n; i++) { int a,b;scanf("%d%d",&a,&b); G[a].push_back(b); G[b].push_back(a); } root=1; dfs(root, -1); printf("%d\n",2*min(dp[root][0],dp[root][1]-1)+1); } return 0;}
- hdu4714 Tree2cycle 树形DP
- 树形 DP hdu4714 Tree2cycle
- hdu4714 Tree2cycle(树形dp)
- hdu4714 Tree2cycle
- hdu4714 Tree2cycle
- hdu4714之树形DP
- hdu4714(树形dp)
- hdu4714 树形dp
- hdu4714 Tree2cycle 树上乱搞
- Tree2cycle hdu4714 贪心
- 树形dp-hdu-4714-Tree2cycle
- hdu 4714 Tree2cycle (树形dp)
- HDU 4714 Tree2cycle(树形dp)
- 树形DP+贪心(乱搞)(HDU4714)
- HDU 4714 Tree2cycle (构造,树形DP)
- HDOJ 题目4714 Tree2cycle(树形DP)
- hdu4714树形DP,用c++交别用g++交
- hdu4714 Tree2cycle 使一棵树变成环最小代价
- fight club
- hdu 4712
- node.js对mongodb的一些操作
- hdu 3259 An interesting mobile game (dfs+bfs+模拟)
- my hibernate note
- hdu4714 Tree2cycle 树形DP
- 飞腾评卷系统单机版上线
- 【Linux配置】:ruijie配置 & eclipse cdt 安装 & grub改变选择菜单等待时间
- XAMPP3.1.0中Apache2.4.3的多站点配置(vhost/virtual host)
- 系统托盘编程完全指南
- 内存溢出与数据库锁表的问题
- 浮点运算和字节对齐
- http://url.cn/VZzfzV百度云推送
- Delphi 文件目录函数大全