Advertisement
Evgeny_Baulin

Homework 2 Task A

Mar 3rd, 2024
669
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9.     int n;
  10.     cin >> n;
  11.  
  12.     vector<vector<int>> graph(n + 1);
  13.     vector<int> distance(n + 1, -1);
  14.  
  15.     for (int i = 2; i <= n; ++i) {
  16.         int parent;
  17.         cin >> parent;
  18.         graph[parent].push_back(i);
  19.     }
  20.  
  21.     queue<int> q;
  22.     q.push(1);
  23.     distance[1] = 0;
  24.  
  25.     while (!q.empty()) {
  26.         int current = q.front();
  27.         q.pop();
  28.  
  29.         for (int child: graph[current]) {
  30.             if (distance[child] == -1) {
  31.                 distance[child] = distance[current] + 1;
  32.                 q.push(child);
  33.             }
  34.         }
  35.     }
  36.  
  37.     int maxDistance = *max_element(distance.begin(), distance.end());
  38.     vector<int> farthestNodes;
  39.     for (int i = 1; i <= n; ++i) {
  40.         if (distance[i] == maxDistance) {
  41.             farthestNodes.push_back(i);
  42.         }
  43.     }
  44.  
  45.     cout << maxDistance << endl;
  46.     cout << farthestNodes.size() << endl;
  47.     for (int node: farthestNodes) {
  48.         cout << node << " ";
  49.     }
  50.     cout << endl;
  51.  
  52.     return 0;
  53. }
  54.  
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement