开启算法笔记
迪杰斯特拉(Dijkstra)算法是典型的最短路径算法,计算一个节点到其他节点的最短路径。
它的主要特点是以起始点为中心向外层扩展(广度优先搜索思想),直到扩展到终点为止。
这是一个按路径长度递增的次序产生最短路径的算法。时间复杂度为 O(n2),n为顶点个数,如果是从其他顶点开始,那么在原有算法的基础上再来一次循环,此时的时间复杂度为O(n3)。
文中使用读取path.txt到输入流中,path.txt文件内容如下:
5 6 1 5
1 5 100
1 2 10
2 5 5
1 3 3
3 4 2
4 5 1
代码:
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
const int maxnum = 300;
const int maxint = 999999;
// 各数组都从下标1开始
int dist[maxnum]; // 表示当前点到源点的最短路径长度
int Gprev[maxnum]; // 记录当前点的前一个结点
int c[maxnum][maxnum]; // 记录图的两点间路径长度
// n -- n nodes
// v -- the source node
// dist[] -- the distance from the ith node to the source node
// prev[] -- the previous node of the ith node
// c[][] -- every two nodes' distance
void Dijkstra(int n, int v, int *dist, int *prev, int c[maxnum][maxnum])
{
bool s[maxnum]; // 判断是否已存入该点到S集合中
for (int i = 1; i <= n; ++i)
{
dist[i] = c[v][i];
s[i] = 0; // 初始都未用过该点
if (dist[i] == maxint)
prev[i] = 0;
else
prev[i] = v;
}
dist[v] = 0;
s[v] = 1;
// 依次将未放入S集合的结点中,取dist[]最小值的结点,放入结合S中
// 一旦S包含了所有V中顶点,dist就记录了从源点到所有其他顶点之间的最短路径长度
// 注意是从第二个节点开始,第一个为源点
for (int i = 2; i <= n; ++i)
{
int tmp = maxint;
int u = v;
// 找出当前未使用的点j的dist[j]最小值
for (int j = 1; j <= n; ++j)
if ((!s[j]) && dist[j]<tmp)
{
u = j; // u保存当前邻接点中距离最小的点的号码
tmp = dist[j];
}
s[u] = 1; // 表示u点已存入S集合中
// 更新dist
for (int j = 1; j <= n; ++j)
if ((!s[j]) && c[u][j]<maxint)
{
int newdist = dist[u] + c[u][j];
if (newdist < dist[j])
{
dist[j] = newdist;
prev[j] = u;
}
}
}
}
// 查找从源点v到终点u的路径,并输出
void searchPath(int *prev, int v, int u)
{
int que[maxnum];
int tot = 1;
que[tot] = u;
tot++;
int tmp = prev[u];
while (tmp != v)
{
que[tot] = tmp;
tot++;
tmp = prev[tmp];
}
que[tot] = v;
for (int i = tot; i >= 1; --i)
if (i != 1)
cout << que[i] << " -> ";
else
cout << que[i] << endl;
}
int searchMax(int *prev, int v, int u)
{
//int tot = 1;
//tot++;
int tmp = prev[u];
int max = c[tmp][u];
while (tmp != v)
{
//que[tot] = tmp;
//tot++;
if (max < c[prev[tmp]][tmp])
max = c[prev[tmp]][tmp];
tmp = prev[tmp];
}
//que[tot] = v;
return max;
}
int main()
{
//freopen("input.txt", "r", stdin);
// 各数组都从下标1开始
// 输入结点数
int n, line, s, t; // 图的结点数和路径数,源点与终点
int i, j;
while (true) {
FILE *fp=freopen("path.txt", "r", stdin);
cin >> n >> line >> s >> t;
{
//line = m;
for (i = 1; i <= n; ++i)
for (j = 1; j <= n; ++j)
c[i][j] = maxint;
int p, q, len; // 输入p, q两点及其路径长度
for (i = 1; i <= line; ++i)//输入数据
{
cin >> p >> q >> len; // 节点p->节点q 路径
if (len < c[p][q]) // 有重边
{
c[p][q] = len; // p指向q
c[q][p] = len; // q指向p,这样表示无向图
}
}
for (i = 1; i <= n; ++i)
dist[i] = maxint;
Dijkstra(n, s, dist, Gprev, c);
// 最短路径长度
cout << "源点到最后一个顶点的最短路径长度: " << dist[t] << endl;
searchPath(Gprev, s, t);//输出路径
cout << searchMax(Gprev, s, t) << endl;//最短路径中的最大权重
}
fclose(fp);
}
return 0;
}
完!