Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <iostream>
- #include <queue>
- using namespace std;
- const int inf = 2000000000;
- vector<vector<int> > g;
- vector<int> d;
- void bfs(int s)
- {
- vector<int> c(d.size());
- c[s] = 1;
- d[s] = 0;
- queue<int> q;
- q.push(s);
- while(!q.empty())
- {
- int u = q.front();
- q.pop();
- for(vector<int>::iterator v = g[u].begin(); v != g[u].end(); v++)
- if(d[*v] > d[u] + 1)
- {
- if(c[*v] == 0)
- q.push(*v);
- c[*v] = 1;
- d[*v] = d[u] + 1;
- }
- }
- }
- int main()
- {
- int n, m, s;
- cin >> n >> m;
- d.resize(n, inf);
- g.resize(n);
- for(int i = 0; i < m; i++)
- {
- int u, v;
- cin >> u >> v;
- u--;v--;
- g[u].push_back(v);
- g[v].push_back(u);
- }
- cin >> s; s--;
- bfs(s);
- for(int i = 0; i < n; i++)
- cout << "d[" << i + 1 << "] = " << d[i] << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment