当前位置:网站首页>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;
}
边栏推荐
- 用OpenPose进行单个或多个人体姿态估计
- C language function review (pass value and address [binary search], recursion [factorial, Hanoi Tower, etc.))
- Spark SQL common time functions
- Outline and box shadow to achieve the highlight effect of contour fillet
- JVM parameter configuration details
- 请问seata中mysql参数每个客户端连接最大的错误允许数量要怎么理解呢?
- 基于OpenCV和YOLOv3的目标检测实例应用
- Spark submission parameters -- use of files
- 死锁杂谈
- Debounce and throttle
猜你喜欢
随机推荐
ML - natural language processing - Basics
在win10系统下使用命令查看WiFi连接密码
args参数解析
Idea remotely submits spark tasks to the yarn cluster
4PAM在高斯信道与瑞利信道下的基带仿真系统实验
获取键盘按下的键位对应ask码
自定义注解校验API参数电话号
JVM-垃圾收集器详解
RedisCluster搭建和扩容
二进制补码
How to understand the maximum allowable number of errors per client connection of MySQL parameters in Seata?
Idea护眼色设置
理解“平均负载”
本地缓存--Ehcache
ML - 图像 - 深度学习和卷积神经网络
Graph theory and concept
你准备好脱离“内卷化怪圈”了吗?
Spark002 --- spark task submission, pass JSON as a parameter
基于OpenCV和YOLOv3的目标检测实例应用
Ml speech depth neural network model









