fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void executeTime() {
  5. cerr << "Time Taken: " << (float)clock() / CLOCKS_PER_SEC << " secs";
  6. }
  7.  
  8. int main() {
  9.  
  10. int n; cin >> n;
  11.  
  12. vector<vector<int>> mp(n + 1);
  13.  
  14. for (int i = 0; i < n - 1; i++) {
  15. int u, v; cin >> u >> v;
  16.  
  17. mp[u].push_back(v);
  18. mp[v].push_back(u);
  19. }
  20.  
  21.  
  22. function<int(int, int)> solve = [&](int src, int p) {
  23.  
  24. int cnt = 0;
  25.  
  26. for (auto &v : mp[src]) {
  27. if (v == p) {
  28. cnt++;
  29. continue;
  30. };
  31.  
  32. int ans = solve(v, src);
  33. if (ans != -1) return ans;
  34.  
  35. cnt += 1;
  36. }
  37.  
  38. if (cnt < 3) return src;
  39.  
  40. return -1;
  41. };
  42.  
  43. int ans = solve(1, -1);
  44.  
  45. cout << ans << endl;
  46.  
  47. executeTime();
  48. return 0;
  49. }
Success #stdin #stdout #stderr 0s 5320KB
stdin
8
1 2
1 3
1 8
2 4
2 5
3 6
6 7
stdout
4
stderr
Time Taken: 0.004281 secs