当前位置:网站首页>CF685B-求有根树每颗子树的重心
CF685B-求有根树每颗子树的重心
2022-07-25 15:23:00 【塔子哥来了】
题目大意:
标题说的很清楚了.
题目思路:
根据树的重心的性质:两颗子树合并,新树重心一定在两个子树重心的连线上.
所以合并子树的时候,让子树们的重心往祖先跳。直到跳到重心结束.
PS:判定重心: 2 * 最大子树sz <= sz[u]即可。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define pb push_back
#define mp make_pair
#define vi vector<int>
#define vll vector<ll>
#define fi first
#define se second
const int maxn = 3e5 + 5;
const int mod = 1e9 + 7;
int sz[maxn] , res[maxn] , f[maxn] , mx[maxn];
vi e[maxn];
void dfs (int u , int fa){
sz[u] = 1; res[u] = u;f[u] = fa;
for (auto & v : e[u]){
if (v == fa) continue;
dfs(v , u);
sz[u] += sz[v];
mx[u] = max(mx[u] , sz[v]);
}
for (auto & v : e[u]){
if (v == fa) continue;
int now = res[v];
// 爆跳
bool ok = false;
do{
int tmx = max(mx[now] , sz[u] - sz[now]);
if (2 * tmx <= sz[u]){
res[u] = now;
ok = true;
break;
}
now = f[now];
if (ok) break;
}while (now != u);
}
return ;
}
int main()
{
ios::sync_with_stdio(false);
int n , m; cin >> n >> m;
for (int i = 2 ; i <= n ; i++) {
int x; cin >> x;
e[x].pb(i);
}
dfs(1 , 0);
for (int i = 1 ; i <= m ; i++){
int x; cin >> x;
cout << res[x] << endl;
}
return 0;
}
边栏推荐
- Iframe nested other website page full screen settings
- ML - Speech - advanced speech model
- Ml speech depth neural network model
- MySQL transactions and mvcc
- What is the Internet of things
- How much memory can a program use at most?
- Es5 thinking of writing inheritance
- ML - 自然语言处理 - 基础知识
- 在win10系统下使用命令查看WiFi连接密码
- Endnote 无法编辑range 解决
猜你喜欢

Application of C language array in Sanzi chess -- prototype of Queen n problem

Reflection - Notes

SVD奇异值分解推导及应用与信号恢复

Spark SQL空值Null,NaN判断和处理

Spark partition operators partitionby, coalesce, repartition

ML - natural language processing - Introduction to natural language processing

Delayed loading source code analysis:

Image cropper example

Spark memory management mechanism new version

什么是物联网
随机推荐
用OpenPose进行单个或多个人体姿态估计
我的创作纪念日
Example of password strength verification
See a lot of blinking pictures on apps, especially the member page
MySQL installation and configuration super detailed tutorial and simple database and table building method
How spark gets columns in dataframe --column, $, column, apply
什么是物联网
JVM-垃圾收集器详解
Spark memory management mechanism new version
SVD奇异值分解推导及应用与信号恢复
Spark SQL null value, Nan judgment and processing
redis淘汰策列
ML - 语音 - 深度神经网络模型
Node learning
Iframe nested other website page full screen settings
获取键盘按下的键位对应ask码
spark中saveAsTextFile如何最终生成一个文件
记一次Yarn Required executor memeory is above the max threshold(8192MB) of this cluster!
Xcode added mobileprovision certificate file error: Xcode encoded an error
反射-笔记