fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5.  
  6.  
  7. const int M = 1000000007;
  8. const int N = 3e5+9;
  9. const int INF = 2e9+1;
  10. const int MAXN = 100000;
  11. const int LINF = 2000000000000000001;
  12.  
  13. //_ ***************************** START Below *******************************
  14.  
  15.  
  16.  
  17.  
  18. vector<vector<int>> tree;
  19.  
  20. void consistency(int n){
  21.  
  22. vector<int> child(n+1, 0); // 1 indexing
  23.  
  24. queue<int> q;
  25. q.push(1);
  26.  
  27. vector<int> visited(n+1, false);
  28. visited[1] = true;
  29.  
  30.  
  31. while(!q.empty()){
  32. auto v = q.front(); q.pop();
  33. int count = 0;
  34. for(int u : tree[v]){
  35. if(visited[u]){
  36. }
  37. else{
  38. q.push(u);
  39. visited[u] = true;
  40. count++;
  41. }
  42.  
  43. }
  44. child[v] = count;
  45. }
  46.  
  47.  
  48.  
  49. for(int i=1; i<=n; i++){
  50. cout << child[i] << " ";
  51. }cout << endl;
  52.  
  53. for(int i=1; i<=n; i++){
  54. if(child[i] == 0) cout << i << " ";
  55. }
  56. }
  57.  
  58.  
  59.  
  60. void solve() {
  61.  
  62. int n;
  63. cin >> n;
  64.  
  65. tree.resize(n+1); // 1 based indexing
  66.  
  67. for(int i=0; i<n-1; i++){
  68. int x, y;
  69. cin >> x >> y;
  70. tree[x].push_back(y);
  71. tree[y].push_back(x);
  72. }
  73.  
  74. consistency(n);
  75.  
  76. }
  77.  
  78.  
  79.  
  80.  
  81.  
  82. int32_t main() {
  83. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  84.  
  85. int t = 1;
  86. while (t--) {
  87. solve();
  88. }
  89.  
  90. return 0;
  91. }
Success #stdin #stdout 0s 5316KB
stdin
5
1 2
1 3
1 4
2 5
stdout
3 1 0 0 0 
3 4 5