Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- vector<int> g[100005];
- struct node {
- int idx, cost, prev_node;
- node () {}
- node(int _idx, int _cost, int pn) {
- idx = _idx;
- cost = _cost;
- prev_node = pn;
- }
- bool operator < (const node &tmp) const {
- if(cost == tmp.cost) {
- return idx < tmp.idx;
- }
- return cost > tmp.cost;
- }
- };
- void find_path(int S, int E, int n) {
- vector<bool> visited(n + 1, false);
- vector<int> dist(n + 1, 2e9);
- vector<int> path(n + 1, -1);
- priority_queue<node> pq;
- pq.push(node(S, 0, -1));
- dist[S] = 0;
- while (!pq.empty()) {
- node c = pq.top();
- pq.pop();
- path[c.idx] = c.prev_node;
- if(c.idx == E) {
- break;
- }
- visited[c.idx] = true;
- for(int i = 0; i < g[c.idx].size(); i++) {
- int neighbour = g[c.idx][i];
- if(!visited[neighbour] and c.cost + 1 < dist[neighbour]) {
- pq.push(node(neighbour, c.cost + 1, c.idx));
- dist[neighbour] = c.cost + 1;
- }
- }
- }
- while(E != S) {
- cout << E + 1 << " ";
- E = path[E];
- }
- cout << S + 1 << endl;
- }
- int main() {
- int n, m;
- cin >> n >> m;
- for(int i = 0; i < m; i++) {
- int a, b;
- cin >> a >> b;
- a--;
- b--;
- g[a].push_back(b);
- g[b].push_back(a);
- }
- priority_queue<node> pq;
- int S, E;
- cin >> S >> E;
- find_path(S - 1, E - 1, n);
- return 0;
- }
- /*
- 5 6
- 1 2
- 1 4
- 4 5
- 2 5
- 2 3
- 2 4
- 1 5
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement