Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include<queue>
- using namespace std;
- #define N 110
- #define INF 1000000
- vector <int> graph[N];
- int way[N];
- int length[N];
- int used[N];
- int n;
- struct El {
- int ver;
- int len;
- El (int v, int l){
- ver = v;
- len = l;
- }
- };
- struct compare
- {
- bool operator()(const El& l, const El& r)
- {
- return l.len > r.len;
- }
- };
- priority_queue<El, vector<El>, compare >heap;
- void bfs(int start) {
- heap.push(El(start,0));
- used[start] = 1;
- while (heap.size() != 0) {
- int v = (heap.top()).ver;
- used[v] = 1;
- heap.pop();
- for (int i = 1; i <= n; i++) {
- if(graph[v][i] != -1 && used[i] == 0){
- heap.push(El(i, graph[v][i]));
- }
- int per = graph[v][i] + length[v];
- if(length[i] != 0 && graph[v][i]!= -1 && length[i] > per ){
- length[i] = per;
- way[i] = v;
- }
- }
- }
- }
- int showWay(int fin){
- if (way[fin] == 0 ) return -1;
- showWay(way[fin]);
- cout<< way[fin] << " " ;
- return 0;
- }
- int main() {
- int start, finish;
- cin >> n >> start >> finish;
- for (int j = 1; j <= n; j++) {
- for (int i = 1; i <= n; i++) {
- int x;
- cin >> x;
- if ( i == 1) { // из-за нумерацию с 1
- graph[j].push_back(-1);
- }
- graph[j].push_back(x);
- }
- }
- for (int i = 1; i <= n; i++) length[i] = INF;
- length[start] = 0;
- if ( start == finish) {
- cout << start << endl;
- return 0;
- }
- bfs(start);
- if ( showWay(finish) == -1 ) {
- cout << "-1";
- } else {
- cout << finish << endl;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment