#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <memory.h>
using namespace std;
int u[20005], v[20005], w[20005];
int Bellman_Ford(int n, int m) //最短路的长度算法 没有队列优化
{
int i;
for (i = 0; i < m * 2; i++)
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
u[i] = a, v[i] = b, w[i] = c;
i++;
u[i] = b, v[i] = a, w[i] = c;
}
int dist[105]; //节点的个数
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
int bak[105];
for (i = 0; i < n - 1; i++)
{
int j, check = 0;
for (j = 0; j < m * 2; j++)
{
if (dist[u[j]] > dist[v[j]] + w[j])
{
dist[u[j]] = dist[v[j]] + w[j];
check = 1;
}
}
if (!check)
break;
}
return dist[n];
}
const int N = 200; // 太大了的话不能运行
int Floyd_Warshall(int n, int m) //简单的三行代码
{
int e[N][N], k, i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (i == j)
{
e[i][j] = 0;
}
else
{
e[i][j] = 0x3f3f3f3f;
}
}
}
for (i = 1; i <= m; i++)
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
if (c < e[a][b])
{
e[a][b] = c;
e[b][a] = c;
}
}
for (k = 1; k <= n; k++)
{
for (i = 1; i <= n; i++)
{
if (e[i][k] == 0x3f3f3f3f)
continue;
for (j = 1; j <= n; j++)
{
if (e[i][j] > e[i][k] + e[k][j])
{
e[i][j] = e[i][k] + e[k][j];
}
}
}
}
return e[1][n];
}
int Dijkstra(int n, int m)
{
int e[105][105], dis[105], book[105], i, j, t1, t2, t3, u, v, min;
int inf = 999999;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (i == j)
e[i][j] = 0;
else
e[i][j] = inf;
}
}
for (i = 1; i <= m; i++)
{
scanf("%d %d %d", &t1, &t2, &t3);
if (e[t1][t2] > t3)
{
e[t1][t2] = t3;
e[t2][t1] = t3;
}
}
for (i = 1; i <= n; i++)
{
dis[i] = e[1][i];
}
for (i = 1; i <= n; i++)
book[i] = 0;
book[1] = 1;
for(i = 1; i <= n - 1; i++)
{
min = inf;
for(j = 1; j <= n; j++)
{
if(book[j] == 0 && dis[j] < min)
{
min = dis[j];
u = j;
}
}
book[u] = 1;
for(v = 1; v <= n; v++)
{
if(e[u][v] < inf)
{
if(dis[v] > dis[u] + e[u][v])
{
dis[v] = dis[u] + e[u][v];
}
}
}
}
return dis[n];
}
int main()
{
int n, m;
while (~scanf("%d %d", &n, &m))
{
printf("%d\n", Dijkstra(n, m));
printf("%d\n", Floyd_Warshall(n, m));
printf("%d\n", Bellman_Ford(n, m));
}
return 0;
}
最短路径的三种方法(全)(另外Bellman的改进再看看)
最新推荐文章于 2022-10-29 18:13:51 发布