【題解】CSES 2079 Finding a Centroid

【題目敘述】https://cses.fi/problemset/task/2079

#include <iostream>
#include <vector>
using namespace std;
 
int n, sz[200005], mx[200005];
vector <int> v[200005];
 
void f(int x, int pre){
    int mx = 0;
    for (int i:v[x]){
        if (i == pre) continue;
        f(i, x);
        sz[x] += sz[i];
        mx = max(mx, sz[i]);
    }
    sz[x] += 1;
    mx = max(mx, n-sz[x]);
    if (mx <= n/2){
        cout << x << "\n";
        exit(0);
    }
}
 
int main() {
    cin >> n;
    for (int i = 1, a, b; i < n; i++){
        cin >> a >> b;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    f(1, 0);
}
分享本文 Share with friends