Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define ll long long
- #define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
- const int MAX = 1e6 + 5;
- vector <int> a[MAX];
- queue <int> q;
- int used[MAX], n, ln[MAX], lm[MAX], x;
- void zero(int n){
- for(int i = 1; i <= n; i++){
- ln[i] = 0;
- used[i] = 0;
- }
- }
- void BFS(int node){
- q.push(node);
- used[node] = 1;
- while(!q.empty()){
- int s = q.front();
- q.pop();
- for(int i : a[s]){
- if(!used[i]){
- q.push(i);
- used[i] = 1;
- ln[i] = ln[s] + 1;
- }
- }
- }
- }
- int main(){
- io;
- cin >> n;
- if(n == 1){
- cout << 1;
- return 0;
- }
- for(int i = 2; i <= n; i++){
- cin >> x;
- a[x].push_back(i);
- a[i].push_back(x);
- }
- BFS(1);
- int d = 0, d1, d2;
- for(int i = 1; i <= n; i++){
- if(ln[i] > d){
- d = ln[i];
- d1 = i;
- }
- }
- d = 0;
- zero(n);
- BFS(d1);
- for(int i = 1; i <= n; i++){
- lm[i] = ln[i];
- if(ln[i] > d){
- d = ln[i];
- d2 = i;
- }
- }
- zero(n);
- BFS(d2);
- int r1 = d / 2;
- int r2 = d / 2;
- if(d % 2 == 1){
- r2++;
- }
- for(int i = 1; i <= n; i++){
- if(ln[i] == r1 && lm[i] == r2){
- cout << i << " ";
- }
- else if(ln[i] == r2 && lm[i] == r1){
- cout << i << " ";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement