【题目来源】
https://www.luogu.com.cn/problem/B3647
【题目描述】
给出一张由 n 个点 m 条边组成的无向图。
求出所有点对 (i,j) 之间的最短路径。
【输入格式】
第一行为两个整数 n,m,分别代表点的个数和边的条数。
接下来 m 行,每行三个整数 u,v,w,代表 u,v 之间存在一条边权为 w 的边。
【输出格式】
输出 n 行每行 n 个整数。
第 i 行的第 j 个整数代表从 i 到 j 的最短路径。
【输入样例】
4 4
1 2 1
2 3 1
3 4 1
4 1 1
【输出样例】
0 1 2 1
1 0 1 2
2 1 0 1
1 2 1 0
【说明/提示】
对于 100% 的数据,n≤100,m≤4500,任意一条边的权值 w 是正整数且 1⩽w⩽1000。
数据中可能存在重边。
【算法分析】
● Floyd 算法(又称 Floyd-Warshall 算法)是一种用于求解所有顶点对之间最短路径的动态规划算法。它适用于带权有向图或无向图,可以处理正权边和负权边(但不能有负权环)。
● 本题数据中可能存在重边,若不处理,会有一个样例不过。
若有重边,处理方法是只保留权值最小的那条边。代码如下:
while(m--) {cin>>a>>b>>c;e[a][b]=min(e[a][b],c); //e[a][b]=c;e[b][a]=min(e[b][a],c); //e[b][a]=c;
}
● 若 e[i][i]<0,则存在负权环。
【算法代码】
#include <bits/stdc++.h>
using namespace std;const int inf=0x3f3f3f3f;
int e[100][100];
int a,b,c;
int n,m;int main() {cin>>n>>m;for(int i=1; i<=n; i++) {for(int j=1; j<=n; j++) {if(i==j) e[i][j]=0;else e[i][j]=inf;}}while(m--) {cin>>a>>b>>c;e[a][b]=min(e[a][b],c); //e[a][b]=c;e[b][a]=min(e[b][a],c); //e[b][a]=c;}for(int k=1; k<=n; k++)for(int i=1; i<=n; i++)for(int j=1; j<=n; j++)if(e[i][j]>e[i][k]+e[k][j])e[i][j]=e[i][k]+e[k][j];for(int i=1; i<=n; i++) {for(int j=1; j<=n; j++) {cout<<e[i][j]<<" ";}cout<<endl;}return 0;
}/*
in:
4 4
1 2 1
2 3 1
3 4 1
4 1 1out:
0 1 2 1
1 0 1 2
2 1 0 1
1 2 1 0
*/
【参考文献】
https://blog.csdn.net/ahalei/article/details/22038539
https://www.cnblogs.com/CLGYPYJ/p/17586069.html