//迪杰斯特拉最短路径算法
//有向图 input:6 9 1 2 7 1 3 9 1 6 14 2 3 10 2 4 15 3 6 2 3 4 11 6 5 9 4 5 6
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
#define MAX 20
#define MAXint 99999
int map[MAX][MAX];
int arr[MAX] = { 0 }; //标记是否已经经被最小访问
//int path[MAX];
struct kk
{
kk() :key(0), val(0){}
int key;
int val;
friend bool operator<(kk a, kk b)
{
return a.val>b.val; //优先级队列逆序优先级的方法:算符重载
}
};
priority_queue<kk> p;
void dijisiter( int n,kk vexkk[])
{
while (!p.empty())
{
kk temless = p.top();
for (int i = 0; i < n; i++)
{
if (map[temless.key][i] != MAXint) //如果路径可达,则将当前起点距离+路径距离存入路径表lenval(只存最小的)
{
if ((vexkk[temless.key].val + map[temless.key][i]) < vexkk[i].val)
{
vexkk[i].val = vexkk[temless.key].val + map[temless.key][i];
}
if (arr[i] == 0) //如果当前顶点未被访问
{
p.push(vexkk[i]); //进入优先级队列
arr[i] = 1;
}
}
}
p.pop();
}
}
int main()
{
int vex, edge, x, y, val;
cin >> vex >> edge;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
map[i][j] = MAXint;
}
kk vexkk[MAX];
for (int i = 0; i < MAX; i++)
{
vexkk[i].val = MAXint;
}
for (int i = 0; i < vex; i++)
{
vexkk[i].key = i;
}
for (int i = 0; i < edge; i++)
{
cin >> x >> y>>val;
map[x - 1][y - 1] = map[y - 1][x - 1]= val;
}
vexkk[0].val = 0;
arr[0] = 1;
p.push(vexkk[0]);
dijisiter( vex, vexkk);
for (int i = 0; i < vex; i++)
{
cout << vexkk[i] .val<< ends;
}
}
优先级队列的应用-----迪杰斯特拉算法
最新推荐文章于 2024-06-27 12:33:00 发布