fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. int main() {
  5.  
  6. int n;
  7. cin>>n;
  8. int e;
  9. cin>>e;
  10.  
  11. vector<int> g[n+1];
  12.  
  13. for(int i=1; i<=e; i++){
  14. int u,v;
  15. cin>>u;
  16. cin>>v;
  17. g[u].push_back(v);
  18. g[v].push_back(u);
  19. }
  20.  
  21. int source = 1;
  22.  
  23. // solution;
  24.  
  25. queue<int> q;
  26.  
  27. q.push(source);
  28.  
  29. vector<int> record (n+1,-1);
  30. record[source]=0;
  31.  
  32. // number of shortes paths:-
  33. vector<int> count(n+1, 0);
  34.  
  35. while(!q.empty()){
  36.  
  37. int t = q.front();
  38.  
  39. q.pop();
  40.  
  41. for(auto x: g[t]){
  42.  
  43. if(record[x]<0){
  44. q.push(x);
  45. record[x] = record[t]+1;
  46. count[x]++;
  47. }
  48. else if(record[x] == record[t]+1){
  49. count[x]++;
  50. }
  51. }
  52.  
  53. }
  54.  
  55. for(int i=1; i<=n; i++){
  56. cout<< count[i]<< " ";
  57. }
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0.01s 5320KB
stdin
9 10 
1 2
2 3
3 6
1 4
4 5
5 6
1 7
7 8
8 9
9 6
stdout
0 1 1 1 1 2 1 1 1