Tree2cycle hdu4714 贪心
来源:互联网 发布:推荐算法 gbdt 编辑:程序博客网 时间:2024/06/11 05:40
Description
给定一棵N个节点的树,去掉这棵树的一条边需要消耗值1,为这个图的两个点加上一条边也需要消耗值1。树的节点编号从1开始。在这个问题中,你需要使用最小的消耗值(加边和删边操作)将这棵树转化为环,不允许有重边。
环的定义如下:
(1)该图有N个点,N条边。
(2)每个顶点的度数为2。
(3)任意两点是可达的。
树的定义如下:
(1)该图有N个点,N-1条边。
(2)任意两点是可达的。
Solution
想到了树链剖分的模型
一棵树是可以分成很多条链的,而这些链又能连成环。那么我们只需要考虑如何去边使得链的数量最少就行了
记节点i的儿子数量为son,那么需要切掉son-2+1条边,记最后剩下tot条链,答案为tot*2+1
良心题库支持扩栈
Code
#pragma comment(linker, "/STACK:102400000,102400000")#include <stdio.h>#define rep(i, st, ed) for (int i = st; i <= ed; i += 1)#define erg(i, st) for (int i = ls[st]; i; i = e[i].next)#define N 1000001#define E N * 2 + 1struct edge{int x, y, next;}e[E];inline int read(){ char ch = getchar(); int x = 0; while (ch < '0' || ch > '9'){ ch = getchar(); } while (ch <= '9' && ch >= '0'){ x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x;}int ind[N], ls[N];inline void addEdge(int &cnt, int x, int y){ cnt += 1; e[cnt] = (edge){x, y, ls[x]}; ls[x] = cnt; ind[y] += 1; cnt += 1; e[cnt] = (edge){y, x, ls[y]}; ls[y] = cnt; ind[x] += 1;}int vis[N], ans;inline int dfs(int now, int fa){ vis[now] = 1; int cnt = 0; erg(i, now){ if (!vis[e[i].y]){ cnt += dfs(e[i].y, now); } } if (cnt >= 2){ ans += cnt - 1; } return cnt < 2;}int main(void){ int n = read(); int edgeCnt = 0; rep(i, 2, n){ int x = read(), y = read(); addEdge(edgeCnt, x, y); } ans = 0; int root; rep(i, 1, n){ if (ind[i] == 1){ root = i; break; } } dfs(root, 0); printf("%d\n", ans * 2 + 1); // printf("%d\n", n * 2 - dis[ans] * 2 + 1); return 0;}
1 0
- Tree2cycle hdu4714 贪心
- hdu4714 Tree2cycle
- hdu4714 Tree2cycle
- hdu4714 Tree2cycle 树形DP
- hdu4714 Tree2cycle 树上乱搞
- 树形 DP hdu4714 Tree2cycle
- hdu4714 Tree2cycle(树形dp)
- hdu4714 Tree2cycle 使一棵树变成环最小代价
- 树形DP+贪心(乱搞)(HDU4714)
- hdu4714之树形DP
- hdu4714(树形dp)
- hdu4714 树形dp
- HDU 4714 Tree2cycle
- hdu 4714 Tree2cycle dp
- hdu 4714 Tree2cycle
- HDU 4714 Tree2cycle
- hdu 4714 Tree2cycle
- hdu 4714 Tree2cycle
- FaceMap项目总结
- Android学习--ListActivity的简单使用以及监听事件
- struct结构在C和C++中的区别
- 最长公共子序列(Longest Common Sequence)
- HDU 6021 MG loves string(容斥原理)——BestCoder Round #93 1003
- Tree2cycle hdu4714 贪心
- 好的学术网站
- 异步加载场景
- 微信公众号开发
- Android群英传读书笔记-2D绘图基础
- Java进阶--深入解析hashmap
- SSL1673 垃圾陷阱(dp)
- Visual Assist X 破解版下载安装
- SSM杰信商务平台项目day02