Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- struct node {
- int idx, cost;
- node () {}
- node(int _idx, int _cost) {
- idx = _idx;
- cost = _cost;
- }
- bool operator < (const node &tmp) const {
- if(cost == tmp.cost) {
- return idx < tmp.idx;
- }
- return cost > tmp.cost;
- }
- };
- int main() {
- int n, m;
- cin >> n >> m;
- vector<int> g[n];
- for(int i = 0; i < m; i++) {
- int a, b;
- cin >> a >> b;
- g[a].push_back(b);
- g[b].push_back(a);
- }
- priority_queue<node> pq;
- int S; // starting node
- cin >> S;
- int E;
- cin >> E; // ending node
- bool visited[n];
- for(int i = 0; i < n; i++) {
- visited[i] = false;
- }
- pq.push(node(S, 0));
- int path[n];
- while (!pq.empty()) {
- node c = pq.top();
- pq.pop();
- 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]) {
- pq.push(node(neighbour, c.cost + 1));
- path[neighbour] = c.idx;
- }
- }
- }
- while(E != S) {
- cout << path[E] << " ";
- E = path[E];
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement