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. //* Parent
  37. }
  38. else{
  39. //* child of Parent
  40. q.push(u);
  41. visited[u] = true;
  42. count++;
  43. }
  44.  
  45. }
  46. child[v] = count;
  47. }
  48.  
  49.  
  50.  
  51. for(int i=1; i<=n; i++){
  52. cout << child[i] << " ";
  53. }cout << endl;
  54.  
  55. for(int i=1; i<=n; i++){
  56. if(child[i] == 0) cout << i << " ";
  57. }
  58. }
  59.  
  60.  
  61.  
  62. void solve() {
  63.  
  64. int n;
  65. cin >> n;
  66.  
  67. tree.resize(n+1); // 1 based indexing
  68.  
  69. for(int i=0; i<n-1; i++){
  70. int x, y;
  71. cin >> x >> y;
  72. tree[x].push_back(y);
  73. tree[y].push_back(x);
  74. }
  75.  
  76. consistency(n);
  77.  
  78. }
  79.  
  80.  
  81.  
  82.  
  83.  
  84. int32_t main() {
  85. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  86.  
  87. int t = 1;
  88. while (t--) {
  89. solve();
  90. }
  91.  
  92. return 0;
  93. }
Success #stdin #stdout 0.01s 5288KB
stdin
5
1 2
1 3
1 4
2 5
stdout
3 1 0 0 0 
3 4 5