frp

BFS

frp
Feb 13th, 2012
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3. #include <queue>
  4. using namespace std;
  5. const int inf = 2000000000;
  6. vector<vector<int> > g;
  7. vector<int> d;
  8. void bfs(int s)
  9. {
  10.     vector<int> c(d.size());
  11.     c[s] = 1;
  12.     d[s] = 0;
  13.     queue<int> q;
  14.     q.push(s);
  15.     while(!q.empty())
  16.     {
  17.         int u = q.front();
  18.         q.pop();
  19.         for(vector<int>::iterator v = g[u].begin(); v != g[u].end(); v++)
  20.             if(d[*v] > d[u] + 1)
  21.             {
  22.                 if(c[*v] == 0)
  23.                     q.push(*v);
  24.                 c[*v] = 1;
  25.                 d[*v] = d[u] + 1;
  26.             }
  27.     }
  28. }
  29. int main()
  30. {
  31.     int n, m, s;
  32.     cin >> n >> m;
  33.     d.resize(n, inf);
  34.     g.resize(n);
  35.     for(int i = 0; i < m; i++)
  36.     {
  37.         int u, v;
  38.         cin >> u >> v;
  39.         u--;v--;
  40.         g[u].push_back(v);
  41.         g[v].push_back(u);
  42.     }
  43.     cin >> s; s--;
  44.     bfs(s);
  45.     for(int i = 0; i < n; i++)
  46.         cout << "d[" << i + 1 << "] = " << d[i] << "\n";
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment