fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n;
  6. cin >> n;
  7.  
  8. vector<vector<int>> graph(n);
  9.  
  10. for (int i = 0; i < n - 1; i++) {
  11. int x, y;
  12. cin >> x >> y;
  13. x--, y--;
  14. graph[x].push_back(y);
  15. graph[y].push_back(x);
  16. }
  17.  
  18. if (graph[0].size() <= 2) {
  19. cout << "Tree can stay rooted at the current root! 1\n";
  20. return 0;
  21. }
  22.  
  23. for (int i = 1; i < n; i++) {
  24. if (graph[i].size() <= 2) {
  25. cout << "Tree should be rerooted to " << i + 1 << "\n";
  26. return 0;
  27. }
  28. }
  29.  
  30. cout << "No valid root exists\n";
  31. return 0;
  32. }
  33.  
Success #stdin #stdout 0.01s 5276KB
stdin
5
1 2
1 3
1 4
1 5
stdout
Tree should be rerooted to 2