【树形DP】Centroid
来源:互联网 发布:新华书店淘宝旗舰店 编辑:程序博客网 时间:2024/06/07 14:32
题目链接http://www.bnuoj.com/bnuoj/contest_show.php?cid=5763#problem/65371
题意:给一棵树,对某个节点定义一个value:删除该结点后,剩下的各连通分量中最大的结点数目。
思路:不需要用二叉树,于是可以直接旋转,从而可以视任何结点为根。于是建树部分就可以直接对输入的边(a-b)限制方向(a->b),让a作为父亲,b作孩子。
我们可以遍历一次该树后,对于每个结点设置一个weight,即以该结点为根的子树的结点数目。
考虑每个结点,如果有g个孩子,那么如果是根,移除后剩g个联通分量,如果不是根,就剩g+1个联通分量。
于是value的求法就是:
对于根,value=max{各孩子的weight}
对于非根结点,value=max{各孩子的weight,根的weight-自身的weight}
PS:上述也可以合并:value[i] = max{weight[孩子], 根weight-自身weight},因为如果是根,上述第二项为0,不影响结果。
#include <cstdio>#include <cstring>#include <vector>#include <climits>#include <algorithm>#include <utility>using namespace std;const int MAX = 16007;struct Node {int id;vector<int> kids;void init() {kids.clear();}} tree[MAX];int weight[MAX];int dp[MAX];int in[MAX]; //入度,入度为0的结点作为根 int n, root;int touch(int root) {if (root <= 0 || root > n) return 0;else {weight[root] = 1;for (int i = 0; i < tree[root].kids.size(); ++i) {weight[root] += touch(tree[root].kids[i]);}return weight[root];}}void DP(int root) {if (root != ::root) {//printf("init %d\n", root);dp[root] = weight[::root] - weight[root];}for (int i = 0; i < tree[root].kids.size(); ++i) {dp[root] = max(dp[root], weight[tree[root].kids[i]]);DP(tree[root].kids[i]);}}int main() {for (int i = 0; i < MAX; ++i) tree[i].id = i;int timer = 0;//while (~scanf(" %d", &n)) {scanf(" %d", &n);for (int i = 0; i <= n; ++i) tree[i].init();memset(in + 1, 0, sizeof(int) * n);int a, b;for (int i = 1; i < n; ++i) {scanf(" %d %d", &a, &b);tree[a].kids.push_back(b);++in[b];}//find rootfor (int i = 1; i <= n; ++i) {if (in[i] == 0) {::root = i;break;}}memset(dp, 0, sizeof(dp));memset(weight, 0, sizeof(weight));weight[root] = touch(root);DP(root);int ans = INT_MAX;for (int i = 1; i <= n; ++i) {if (dp[i] < ans) ans = dp[i];}vector<int> v;for (int i = 1; i <= n; ++i) {if (dp[i] == ans) {v.push_back(i);}}printf("%d %d\n", ans, v.size());for (int i = 0; i < v.size(); ++i) {printf("%d%c", v[i], (i == v.size() - 1 ? '\n' : ' '));}//}return 0;}
0 0
- 【树形DP】Centroid
- SGU 134 Centroid(树形dp)
- SGU 134 Centroid 树形DP
- SGU - 134 Centroid 无根树转有根树 + 树形DP
- SGU 134 Centroid(树形DP)
- SGU 134 Centroid (树形dp 求树的中心)
- [HDOJ 4863] Centroid of a Tree [树形DP]
- hdu 4863 Centroid of a Tree(树形dp)
- SGU134 Centroid 树形DP基础题,求树的重心
- HDU 4863 Centroid of a Tree (树形dp)
- 【HDU 4863 多校联合】Centroid of a Tree【树形DP】
- hdoj 4863 Centroid of a Tree【树的重心+树形dp+数据结构】
- 树的重心DP HDU4863 Centroid of a Tree
- 树形dp
- 树形DP
- 树形dp
- 树形DP
- 树形dp
- @JsonIgnoreProperties(value={"hibernateLazyInitializer"}) 属性
- JAVA之旅——重温Java关键词2
- STM32F411RE Nucleo笔记-按键控制PWM占空比
- HDU1213 How Many Tables 【标准并查集】
- SDL 1.2版本显示YUYV422数据
- 【树形DP】Centroid
- [JNI]如何在ANDROID JNI 的C++中打Log
- 关于linux kernel里的high memory
- Controlling How NSThread and NSRunLoop Exit
- IOS中的WebView
- Sicily 1036. Crypto Columns
- 读取JSON字符串,转为XML文件(二)
- Phoenix常见问题解答
- 何以笙箫默