fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5.  
  6. int n,e;
  7. cin >> n >> e;
  8.  
  9. vector<vector<int>> g(n+5);
  10.  
  11. for (int i = 0; i < e; i++){
  12. int a, b;
  13. cin >> a >> b;
  14. g[a].push_back(b);
  15. g[b].push_back(a);
  16. }
  17.  
  18. int source; cin >> source;
  19.  
  20. unordered_map<int, bool> visited;
  21. queue<int> q;
  22. unordered_map<int, int> level;
  23. unordered_map<int, int> ways;
  24. // vector<int> ways(n+5, 0);
  25.  
  26. q.push(source);
  27. visited[source] = true;
  28. level[source] = 0;
  29. ways[source] = 1;
  30.  
  31. while(!q.empty()){
  32.  
  33. int parent = q.front();
  34. q.pop();
  35.  
  36. for(auto child : g[parent]){
  37.  
  38. if(visited[child] == false){
  39. q.push(child);
  40. visited[child] = true;
  41. level[child] = level[parent]+1;
  42. ways[child] = ways[parent];
  43. }
  44.  
  45. else if(level[child] == level[parent] + 1){
  46. ways[child] = ways[child] + ways[parent];
  47. }
  48.  
  49. }
  50.  
  51.  
  52. }
  53.  
  54. for (int i = 1; i <= n; i++){
  55. if(visited[i] == true){
  56. cout << "No ways shortest way to reach " << i << " : " <<ways[i] << endl;
  57. }
  58. }
  59.  
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 5320KB
stdin
7 7
1 2
1 3
2 4
3 6
6 5
4 5
5 7
1
stdout
No ways shortest way to reach 1 : 1
No ways shortest way to reach 2 : 1
No ways shortest way to reach 3 : 1
No ways shortest way to reach 4 : 1
No ways shortest way to reach 5 : 2
No ways shortest way to reach 6 : 1
No ways shortest way to reach 7 : 2