fork download
  1. #include <iostream>
  2. #include<bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. //graph bfs
  7. int main() {
  8. // your code goes here
  9. int n ; int m ;
  10. cin>>n>>m;
  11. vector<vector<int>>adj(n+1);
  12. vector<bool>vis(n+1,false);
  13. int level[n+1];
  14. for(int i = 0 ; i < m ; i++){
  15. int u ; int v ;
  16. cin>>u>>v;
  17. adj[u].push_back(v);
  18. adj[v].push_back(u);
  19. }
  20.  
  21. int src = 1;
  22. vis[src]=true;
  23. queue<int>q;
  24. q.push(src);
  25. int child[n+1];
  26.  
  27. while(!q.empty()){
  28. int curr = q.front();
  29. q.pop();
  30. int count = 0 ;
  31. for(auto adjacent : adj[curr]){
  32. if(!vis[adjacent]){
  33. vis[adjacent]=true;
  34. q.push(adjacent);
  35. count++;
  36. }
  37. }
  38. child[curr]=count;
  39. }
  40.  
  41. for(int i = 1 ; i<=n;i++) cout<<child[i]<<endl;
  42.  
  43. for(int i = 1 ; i<=n;i++){
  44. if(child[i]==0) cout<<i<<" ";
  45. }
  46.  
  47. return 0 ;
  48. }
Success #stdin #stdout 0.01s 5312KB
stdin
8 7 
1 2 
1 3
2 4 
2 5 
3 6 
3 7 
3 8
stdout
2
2
3
0
0
0
0
0
4 5 6 7 8