首页 > 其他分享 >CF685B Kay and Snowflake

CF685B Kay and Snowflake

时间:2022-10-25 15:36:00浏览次数:69  
标签:fr int siz ca CF685B son Kay include Snowflake


题目链接:​​传送门​​ 给出q组询问每次求以这个点为根的子树的重心,n,q<=300000

树的重心的一个性质:每棵的子树的大小都不超过整个树大小的一半
具体细节看代码实现


*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <complex>
#include <algorithm>
#include <climits>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define
#define

using namespace std;
typedef long long ll;
struct node {
int next, to;
}e[A];
int head[A], num;
void add(int fr, int to) {
e[++num].next = head[fr];
e[num].to = to;
head[fr] = num;
}
int n, q, a, siz[A], son[A], fa[A];
void dfs(int fr) {
son[fr] = fr; siz[fr] = 1;
for (int i = head[fr]; i; i = e[i].next) {
int ca = e[i].to;
if (ca == fa[fr]) continue;
dfs(ca);
siz[fr] += siz[ca];
}
for (int i = head[fr]; i; i = e[i].next) {
int ca = e[i].to;
if (ca == fa[fr]) continue;
if (siz[ca] * 2 > siz[fr]) son[fr] = son[ca]; //在子树中初步找重心
}
while ((siz[fr] - siz[son[fr]]) * 2 > siz[fr]) son[fr] = fa[son[fr]]; //当前节点的重心在子树重心到当前节点的路径上,根据性质判断重心
}

int main(int argc, char const *argv[]) {
cin >> n >> q;
for (int i = 2; i <= n; i++) cin >> fa[i], add(i, fa[i]), add(fa[i], i);
dfs(1);
while (q--) {
cin >> a;
cout << son[a] << endl;
}
return 0;
}


标签:fr,int,siz,ca,CF685B,son,Kay,include,Snowflake
From: https://blog.51cto.com/lyle/5794777

相关文章

  • Python 和 Snowflake:使用配置文件
    Python和Snowflake:使用配置文件注意:虽然强烈建议在虚拟环境中运行Python,但设置此venv不在本文的范围内。也许我会在稍后阶段解决这个问题。现在我正在为此目的使用A......
  • 分布式自增ID算法Snowflake简介
    背景过去的项目开发中,我们常常选用的数据库是mysql,mysql以其体积小、速度快等优势,备受中小型项目的青睐。随着项目数据量的迅速增长,mysql已无法满足我们的项目需求,数据迁移......
  • 全局唯一ID生成器(SnowFlakeId算法JAVA实现)
    importorg.apache.commons.lang3.RandomUtils;importjava.util.Random;/***@Description:全局唯一Id生成器*@Author:yk*@Create:2022-09-2016:55*/p......
  • (转)基于.NET Standard的分布式自增ID算法--Snowflake
    转自:https://www.lmlphp.com/user/1222/article/item/15683/概述本篇文章主要讲述分布式ID生成算法中最出名的Snowflake算法。搞.NET开发的,数据库主键最常见的就是int类......
  • 一篇文章彻底搞懂snowflake算法及百度美团的最佳实践
    写在前面的话一提到分布式ID自动生成方案,大家肯定都非常熟悉,并且立即能说出自家拿手的几种方案,确实,ID作为系统数据的重要标识,重要性不言而喻,而各种方案也是历经多代优化......