fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n, m;
  6. cin>>n>>m;
  7. vector<int> adjList[n];
  8. for(int i=0;i<m;i++){
  9. int x,y;
  10. cin>>x>>y;
  11. adjList[x].push_back(y);
  12. adjList[y].push_back(x);
  13. }
  14.  
  15. int source=1;
  16. vector<int> visited(n, 0);
  17. vector<int> level(n, 0);
  18. vector<int> ways(n, 0);
  19. queue<int> q;
  20. q.push(source);
  21. visited[source]=1;
  22. ways[source]=1;
  23. while(!q.empty()){
  24. int node=q.front();
  25. q.pop();
  26. visited[node]=1;
  27. for(auto adjNode : adjList[node]){
  28. if(!visited[adjNode]){
  29. //first time visit
  30. visited[adjNode]=1;
  31. level[adjNode]=level[node]+1;
  32. ways[adjNode]=ways[node];
  33. q.push(adjNode);
  34. }
  35. else{
  36. if(level[adjNode]==level[node]+1){
  37. //node adjNode is on shortest path
  38. ways[adjNode]=ways[adjNode]+ways[node];
  39. }
  40. else{
  41. //node adjNode is not on the shortest path
  42. //no need to count
  43. }
  44. }
  45. }
  46. }
  47. for(int i=0;i<ways.size();i++){
  48. cout<<"node "<<i<<" : "<<ways[i];
  49. cout<<"\n";
  50. }
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0s 5296KB
stdin
5 5
1 2
1 3
2 4
3 4
4 0
stdout
node 0 : 2
node 1 : 1
node 2 : 1
node 3 : 1
node 4 : 2