codeforces 686D(树的重心)
来源:互联网 发布:java web的区别 编辑:程序博客网 时间:2024/05/17 07:23
原来完全没有学过树的重心的性质,看数据量大,知道只能跑一次dfs然后O(1)查询,自己瞎搞了半天一直wa。后来学习了树的重心,知道了一些性质。
树的重心的性质:
性质 1 :树中所有点到某个点的距离和中,到重心的距离和是最小的,如果有两个距离
和,他们的距离和一样。
性质 2 :把两棵树通过某一点相连得到一颗新的树,新的树的重心必然在连接原来两棵
树重心的路径上。
性质 3 :一棵树添加或者删除一个节点,树的重心最多只移动一条边的位置。
这样利用性质2,就可以每次回溯的时候,把子节点的子树当做一棵树,然后父节点和除这个子节点以外的其他子节点当做一个树,这两棵树相连,重心一定在两棵树重心的路径上,然后通过父子关系,往上找。#include<cstdio>#include<vector>#include<cstring>using namespace std;const int maxn = 300005;int par[maxn];int dp[maxn];int ans[maxn];vector<int>G[maxn];void dfs(int u){ dp[u] = 1; ans[u] = u; int len = G[u].size(); for(int i=0;i<len;i++) { int v = G[u][i]; dfs(v); dp[u]+=dp[v]; } for(int i=0;i<len;i++) { int v = G[u][i]; if(dp[v]*2>dp[u]) { ans[u] = ans[v]; } } while((dp[u]-dp[ans[u]])*2>dp[u]) { ans[u] = par[ans[u]]; }}int main(){ int n,m; scanf("%d%d",&n,&m); for(int i=2;i<=n;i++) { scanf("%d",&par[i]); G[par[i]].push_back(i); } memset(dp,0,sizeof(dp)); dfs(1); int q; while(m--) { scanf("%d",&q); printf("%d\n",ans[q]); } return 0;}
树的重心,模板
typedef long long ll;typedef pair<int, int> pll;const int INF = 0x3f3f3f3f;const int MAXN = 100000 + 10;int n;/* 树的重心 * 初始化 vis[] son[] 为 0 * 初始化 sz 为 INF */int zx, sz;int son[MAXN], vis[MAXN];vector<pll> edge[MAXN];void init(){ for (int i = 1; i <= n; i++) { edge[i].clear(); } memset(vis, 0, sizeof(vis)); sz = INF; zx = -1;}void dfs(int r){ vis[r] = 1; son[r] = 0; int tmp = 0; for (int i = 0; i < edge[r].size(); i++) { int v = edge[r][i].second; if (!vis[v]) { dfs(v); son[r] += son[v] + 1; tmp = max(tmp, son[v] + 1); } } tmp = max(tmp, n - son[r] - 1); if (tmp < sz) { zx = r; sz = tmp; }}
阅读全文
0 0
- codeforces 686D(树的重心)
- 【CodeForces 686 D. 】 【树的重心性质】
- codeforces 686D. Kay and Snowflake 树的重心应用
- Codeforces 686 D Kay and Snowflake【树的重心】
- codeforces 679D 树的重心
- Codeforces 686 D Kay and Snowflake (树重心)
- Codeforces Round #359 (Div. 2)D. Kay and Snowflake【树的重心】
- Codeforces Round #359 (Div. 2)D. Kay and Snowflake【树的重心】
- poj3107(树的重心)
- poj1655(树的重心)
- codeforces686D(树的重心)
- 树的重心(模板)
- Codeforces 685B Kay and Snowflake 树的重心
- Codeforces 685B Kay and Snowflake(树的重心)
- Codeforces 701E Connecting Universities【树的重心】
- 求树的重心(POJ1655)
- poj1655Balancing Act(树的重心)
- SGU 134 Centroid(树的重心)
- C++学习-存储的持续性与作用域
- #ifndef/#define/#endif详解
- python爬取页面常用的正则表达
- HDU1091-A+B for Input-Output Practice (III)
- 自定义表情面板
- codeforces 686D(树的重心)
- 648. Replace Words
- 如何选择机器学习算法的简单线路图
- rownum用法详解
- org.slf4j.Logger找不到
- 技术点-类加载器-理解
- java上传与下载
- Servlet初相识
- MySQL 基本操作查询