Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define ll long long
- #define SZ(v) ((int)(v).size())
- #define pb push_back
- const int N = 2e5+9;
- const int inf = 1e9+9;
- vector<int> adj[N];
- vector<int> BFSPath (int st_node, int target) {
- queue<int> q;
- q.push(st_node);
- vector<int> level(N, -1);
- vector<int> parent(N, -1);
- level[st_node] = 0;
- int cur_node, depth = 0, sz_q = SZ(q);
- bool found = false;
- for (; !q.empty() && not found; ++depth, sz_q = SZ(q)) {
- while (sz_q--) {
- cur_node = q.front();
- q.pop();
- for (int child : adj[cur_node]) {
- if (level[child] == -1) {
- level[child] = depth + 1;
- q.push(child);
- parent[child] = cur_node;
- // check parent
- if (child == target) {
- // found
- found = true;
- break;
- }
- }
- }
- }
- }
- // get_path
- vector<int> path;
- while (target != -1) { // fail -> target = -1
- path.push_back(target);
- target = parent[target];
- }
- // 5 4 3 1
- reverse(path.begin(), path.end());
- return path;
- }
- void run () {
- int n, m;
- cin >> n >> m;
- for (int i = 0; i < m; ++i) {
- int u, v;
- cin >> u >> v;
- adj[u].push_back(v);
- adj[v].push_back(u);
- }
- vector<int> dist;
- dist = BFSPath(1, 5);
- for (int i = 0; i < SZ(dist); ++i)
- cout << dist[i] << " ";
- }
- int main () {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- freopen("/home/hamoudi/clion/hello.in", "rt", stdin);
- int tt;
- tt = 1;
- // cin >> tt;
- while (tt--)
- run();
- return 0;
- }
- /*
- 1 -> 0
- 2 3 -> 1
- 4 -> 2
- 5 -> 3
- 1 3 4 5
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement