VasilM

bfs gora

Mar 19th, 2014
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. const int MAXN = 1000;
  5. int used[MAXN+1], Q[MAXN], P[MAXN], G[MAXN][MAXN], N, b, e;
  6.  
  7. void make_empty(){
  8.     b=0;
  9.     e=-1;
  10. }
  11.  
  12. void push(int x){
  13.     Q[++e]=x;
  14. }
  15.  
  16. int pop(){
  17.     return Q[b++];
  18. }
  19.  
  20. bool emptyQ(){
  21.     return b>e;
  22. }
  23.  
  24. void BFS(int r){
  25.   int  x,y,i;
  26.  
  27.   for(i=1;i<=N;i++) used[i]=0;
  28.   make_empty();
  29.   push(r);
  30.   used[r]=1;
  31.   P[r]=0;
  32.  
  33.   while(!emptyQ()){
  34.     x=pop();
  35.     for(i=1;i<=G[x][0];i++){
  36.       y=G[x][i];
  37.       if(!used[y]){
  38.         push(y);
  39.         used[y]=1;
  40.         P[y]=x;
  41.         cout<< y <<" ";
  42.       }
  43.     }
  44.   }
  45. }
  46.  
  47.  
  48. int main(){
  49.  
  50.     setlocale(0,"");
  51.     int n,x,y;
  52.  
  53.     while( cin >> n ){
  54.  
  55.         for( int i=0; i<n; i++ ){
  56.             cin >> y >> x;
  57.             G[x][++G[x][0]] = y;
  58.             G[y][++G[y][0]] = x;
  59.         }
  60.     }
  61.  
  62.     cout << 1 << " ";
  63.     BFS(1);
  64.     cout << endl;
  65.  
  66.     for(int i=1; i<n; i++){
  67.        if(used[i] != 1){
  68.            cout << "Графа не е свързан! Следващо дърво:\n";
  69.            cout << i << " ";
  70.            BFS(i);
  71.            cout << endl;
  72.        }
  73.     }
  74.  
  75.     return 0;
  76. }
  77. /*
  78. примерен вход
  79. 18
  80.  1 2
  81.  2 3
  82.  1 4
  83.  3 5
  84.  6 7
  85.  6 8
  86.  7 9
  87.  9 10
  88.  11 12
  89.  11 13
  90.  15 12
  91.  14 16
  92.  14 17
  93. */
Advertisement
Add Comment
Please, Sign In to add comment