CodeForces 686D Kay and Snowflake

题目链接:CodeForces 686D Kay and Snowflake

题目大意:

题解:
一个树的重心,只会在根本身或者最大的子树当中产生。
先判断当前根能否作为重心,如果不能,就从最大的子树的重心往上面找。

#include <iostream>
#include <vector>
using namespace std;

int n, q, child[300010], Size[300010], res[300010], fa[300010];
vector<int> g[300010];

void dfs(int x) {
    Size[x] = 1;
    for (int i = 0; i < g[x].size(); ++i) {
        dfs(g[x][i]);
        Size[x] += Size[g[x][i]];
        if (Size[g[x][i]] > Size[child[x]]) {
            child[x] = g[x][i];
        }
    }
    if (Size[child[x]] * 2 > Size[x]) {
        int now = res[child[x]];
        while ((Size[x] - Size[now]) * 2 > Size[x]) {
            now = fa[now];
        }
        res[x] = now;
    } else {
        res[x] = x;
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin >> n >> q;
    for (int i = 2, x; i <= n; i++) {
        cin >> x;
        fa[i] = x;
        g[x].push_back(i);
    }
    dfs(1);
    while (q--) {
        int x;
        cin >> x;
        cout << res[x] << endl;
    }
    return 0;
}
posted @ 2022-02-02 14:27  ZZHHOOUU  阅读(26)  评论(0编辑  收藏  举报