当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

Run redis on docker to start in the form of configuration file, and the connection client reports an error: server closed the connection

Overview of JS synchronous, asynchronous, macro task and micro task

ML - 语音 - 高级语音模型

Spark SQL null value, Nan judgment and processing

matlab--CVX优化工具包安装

伤透脑筋的CPU 上下文切换

Spark 内存管理机制 新版

ML - 语音 - 传统语音模型

Idea护眼色设置

How to solve the login problem after the 30 day experience period of visual stuido2019
随机推荐
你准备好脱离“内卷化怪圈”了吗?
Is it safe to open futures online? Which company has the lowest handling charge?
Spark002 --- spark task submission, pass JSON as a parameter
Outline and box shadow to achieve the highlight effect of contour fillet
Idea护眼色设置
Redis elimination strategy list
How spark gets columns in dataframe --column, $, column, apply
数据系统分区设计 - 分区再平衡(rebalancing)
Understanding the execution order of T-SQL query from the execution order of join on and where
Idea remotely submits spark tasks to the yarn cluster
Application of C language array in Sanzi chess -- prototype of Queen n problem
Spark提交参数--files的使用
ML - 自然语言处理 - 关键技术
See a lot of blinking pictures on apps, especially the member page
VMware Workstation fails to start VMware authorization service when opening virtual machine
分布式原理 - 什么是分布式系统
Args parameter parsing
Once spark reported an error: failed to allocate a page (67108864 bytes), try again
获取键盘按下的键位对应ask码
The development summary of the function of fast playback of audio and video in any format on the web page.