DS图—图的最短路径
题目描述
给出一个图的邻接矩阵,输入顶点v,用迪杰斯特拉算法求顶点v到其它顶点的最短路径。
输入
第一行输入t,表示有t个测试实例
第二行输入顶点数n和n个顶点信息
第三行起,每行输入邻接矩阵的一行,以此类推输入n行
第i个结点与其它结点如果相连则为距离,无连接则为0,数据之间用空格
隔开。第四行输入v0,表示求v0到其他顶点的最短路径距离
以此类推输入下一个示例
输出
对每组测试数据,输出:
每行输出v0到某个顶点的最短距离和最短路径
每行格式:v0编号-其他顶点编号-最短路径值----[最短路径]。没有路径输出:v0编号-其他顶点编号–1。具体请参考示范数据
样例输入
2
5 0 1 2 3 4
0 5 0 7 15
0 0 5 0 0
0 0 0 0 1
0 0 2 0 0
0 0 0 0 0
0
6 V0 V1 V2 V3 V4 V5
0 0 10 0 30 100
0 0 5 0 0 0
0 0 0 50 0 0
0 0 0 0 0 10
0 0 0 20 0 60
0 0 0 0 0 0
V0
样例输出
0-1-5----[0 1 ]
0-2-9----[0 3 2 ]
0-3-7----[0 3 ]
0-4-10----[0 3 2 4 ]
V0-V1–1
V0-V2-10----[V0 V2 ]
V0-V3-50----[V0 V4 V3 ]
V0-V4-30----[V0 V4 ]
V0-V5-60----[V0 V4 V3 V5 ]
#include <iostream>
#include <queue>
#include <vector>
#include <stack>
#include <algorithm>
#include <map>
#include <unordered_map>
using namespace std;
class Node {
public:
int loc, prev, cost;
Node(int loc, int prev, int cost) :loc(loc), prev(prev), cost(cost) {
;
}
};
struct cmp {
bool operator ()(Node a, Node b) {
return a.cost > b.cost;
}
};
int main() {
int t;
cin >> t;
while (t--) {
priority_queue<Node,vector<Node>,cmp> pq;
int n;
cin >> n;
vector<int> visited(n, 0);
vector<int> distance(n, 999999);
unordered_map<int, int> check;
vector<int> father(n, -1);
vector<vector<int>> matrx(n, visited);
for (int i = 0;i < n;i++) {
for (int j = 0;j < n;j++) {
cin >> matrx[i][j];
}
}
int start = 0;
cin >> start;
int index = 0;
cin >> index;
pq.push({start,start,0});
int counter = -1;
int tmp = -1;
vector<int> res;
while (!pq.empty()) {
Node cur = pq.top();
pq.pop();
if (visited[cur.loc])continue;
counter++;
if (counter == index) {
tmp = cur.cost;
res.push_back(cur.loc);
}
else if (cur.cost == tmp) res.push_back(cur.loc);
// cout <<"counter=:"<<counter<< " index" << cur.loc << " prev=" << cur.prev << " cost=" << cur.cost << endl;
visited[cur.loc] = 1;
father[cur.loc] = cur.prev;
distance[cur.loc] = cur.cost;
check[cur.cost] = cur.loc;
for (int i = 0;i < n;i++) {
if (visited[i]) continue;
else if (matrx[cur.loc][i] != 0) {
pq.emplace(i, cur.loc, cur.cost + matrx[cur.loc][i]);
}
}
}
sort(res.begin(), res.end());
for (auto it : res) {
if (it != *res.begin()) {
cout << " ";
}
cout << it;
}
cout << endl;
}
}
```cpp
在这里插入代码片