Advertisement
istinishat

BFS

Jun 3rd, 2016
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <queue>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. #define si(a) scanf("%d",&a)
  10. #define f first
  11. #define s second
  12. #define mp(a,b) make_pair(a,b)
  13. #define MAX 1005
  14.  
  15. int dist[MAX];
  16. vector<int> graph[MAX];
  17.  
  18. void bfs(int st)
  19. {
  20.     queue<pair<int,int> > Q;
  21.     Q.push(mp(st,0));
  22.     memset(dist,-1,sizeof(dist));
  23.     while(!Q.empty()){
  24.         pair<int,int> now=Q.front();
  25.         Q.pop();
  26.         if(dist[now.f]!=-1)
  27.             continue;
  28.         dist[now.f]=now.s;
  29.         //cout<<now.f+1<<" "<<now.s<<endl;
  30.         for(int i=0;i<graph[now.f].size();i++)
  31.             Q.push(mp(graph[now.f][i],now.s+1));
  32.     }
  33.     return ;
  34. }
  35.  
  36. int main()
  37. {
  38.     //freopen("input","r",stdin);
  39.     int n,m,i;
  40.     si(n);si(m);
  41.     for(i=0;i<m;i++){
  42.         int u,v;
  43.         si(u);si(v);
  44.         u--;v--;
  45.         graph[u].push_back(v);
  46.         graph[v].push_back(u);
  47.     }
  48.     bfs(0);
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement