forked from Jonathan-Uy/CSES-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFinding a Centroid.cpp
More file actions
45 lines (36 loc) · 798 Bytes
/
Finding a Centroid.cpp
File metadata and controls
45 lines (36 loc) · 798 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
using namespace std;
const int maxN = 2e5+5;
int N, a, b, p[maxN], sz[maxN];
vector<int> G[maxN];
void dfs(int u = 1){
sz[u] = 1;
for(int v : G[u]){
if(v != p[u]){
p[v] = u;
dfs(v);
sz[u] += sz[v];
}
}
}
int main(){
scanf("%d", &N);
for(int i = 0; i < N-1; i++){
scanf("%d %d", &a, &b);
G[a].push_back(b);
G[b].push_back(a);
}
dfs();
for(int i = 1; i <= N; i++){
bool centroid = true;
if(p[i] != 0 && N-sz[i] > N/2)
centroid = false;
for(int v : G[i])
if(v != p[i] && sz[v] > N/2)
centroid = false;
if(centroid){
printf("%d\n", i);
return 0;
}
}
}