Tranvick

BFS

Dec 1st, 2011
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. #include <queue>
  2. using namespace std;
  3. #include <cstdio>
  4. #define N 1111
  5. #define M 111111
  6.  
  7. int n,m,ef[M],es[M],first[N],next[M],c,d[N],S,T;
  8. bool b[N];
  9. queue<int> q;
  10.  
  11. void add(int x,int y){
  12.     next[++c]=first[x];first[x]=c;
  13.     ef[c]=x;es[c]=y;
  14. }
  15.  
  16. void bfs(int x){
  17.     b[x]=1;q.push(x);
  18.     while (!q.empty()){
  19.         int v=q.front();q.pop();
  20.         for (int h=first[v];h;h=next[h])
  21.             if (!b[es[h]]){
  22.                 b[es[h]]=1;
  23.                 d[es[h]]=d[v]+1;
  24.                 q.push(es[h]);
  25.             }
  26.     }
  27. }
  28.  
  29. int main(){
  30.     scanf("%d%d%d%d",&n,&m,&S,&T);
  31.     for (int i=1;i<=m;i++){
  32.         int x,y;
  33.         scanf("%d%d",&x,&y);
  34.         add(x,y);
  35.     }
  36.     bfs(S);
  37.     printf("%d",d[T]);
  38.     return 0;
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment