fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define endl '\n'
  4. #define int long long
  5. const int MOD = pow(10,9)+7;
  6. const int MOD2 = 998244353;
  7. const int INF = LLONG_MAX/2;
  8.  
  9. int primes[1000000];
  10.  
  11. void seive(){
  12. fill(primes, primes + 1000000, 1);
  13. primes[0] = primes[1] = 0;
  14. for(int i = 2 ; i*i < 1000000 ; i++){
  15. if(primes[i]){
  16. for(int j = i*i ; j < 1000000 ; j += i){
  17. primes[j] = 0;
  18. }
  19. }
  20. }
  21. for(int i = 1 ; i < 1000000 ; i++){
  22. primes[i] += primes[i-1];
  23. }
  24. }
  25. int factorial(int n){
  26. if(n==0){
  27. return 1;
  28. }
  29. return (n*(factorial(n-1)))%MOD;
  30. }
  31. bool isPrime(int n){
  32. if(n <= 1) return false;
  33. for(int i = 2 ; i*i <= n ; i++){
  34. if(n % i == 0) return false;
  35. }
  36. return true;
  37. }
  38.  
  39. int power(int a, int b){
  40. if(b == 0) return 1;
  41. a %= MOD;
  42. int value = power(a, b / 2);
  43. if(b % 2 == 0){
  44. return (value * value) % MOD;
  45. } else {
  46. return ((value * value) % MOD * (a % MOD)) % MOD;
  47. }
  48. }
  49.  
  50. int gcd(int a, int b){
  51. if(a == 0) return b;
  52. return gcd(b % a, a);
  53. }
  54. void solve() {
  55. int n1;
  56. cin>>n1;
  57. vector<int>A[n1+1];
  58. for(int i = 0 ; i<n1-1 ; i++){
  59. int a,b;
  60. cin>>a>>b;
  61. A[a].push_back(b);
  62. A[b].push_back(a);
  63. }
  64. int d;
  65. cin>>d;
  66. queue<int>q;
  67. int visited[n1+1] = {0};
  68. int children[n1+1]={0};
  69. visited[d] = 1;
  70. q.push(d);
  71. while(!q.empty()){
  72. int node = q.front();
  73. q.pop();
  74. for(auto node1 : A[node]){
  75. if(!visited[node1]){
  76. q.push(node1);
  77. visited[node1] = 1;
  78. children[node] = children[node]+1;
  79. }
  80. else{
  81. //parent
  82. }
  83. }
  84. }
  85. if(children[d]==3){
  86. cout<<"The vertices that can be placed as root to make a valid binary tree is as follows: ";
  87. for(int i = 1 ; i<=n1 ; i++){
  88. if(children[i]==0){
  89. cout<<i<<" ";
  90. }
  91. }
  92. cout<<endl;
  93. }
  94. else{
  95. cout<<"It is already a valid binary tree"<<endl;
  96. }
  97. }
  98.  
  99. signed main(){
  100. ios::sync_with_stdio(false); cin.tie(NULL);
  101. //int t;
  102. //cin >> t;
  103. //while(t--){
  104. solve();
  105. //}
  106. return 0;
  107. }
Success #stdin #stdout 0.01s 5320KB
stdin
8
1 2
1 3
1 4
2 5
3 6
3 7 
4 8
1
stdout
The vertices that can be placed as root to make a valid binary tree is as follows: 5 6 7 8