跳到正文

个人记录

B3647 Floyed 题解

Pianmu约 2 分钟
原文
文章信息与版本

文章信息

发布
2023年11月17日
收录
2026年9月23日
更新
2026年11月5日
篇幅
约 2 分钟

版本

  1. v1当前

本题考查最短路径算法Floyed,根据数据量n<=10可推断本题使用时间的复杂度n^3的Floyed并不会超时。
值得注意的是,Floyed算法核心部分中,最外层循环为代表松弛的变量!

C++
# include <bits/stdc++.h>
using namespace std;
const int inf=0x3f;
const int maxn=105;
int dist[maxn][maxn];
int n,m;
int main()
{
	scanf("%d%d",&n,&m);
	memset(dist,inf,sizeof(dist));
	for (int i=1;i<=n;i++)
	{
		dist[i][i]=0;
	}
	//the map should be started filled with inf and 0
	for (int i=1;i<=m;i++)
	{
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		dist[u][v]=min(dist[u][v],w); //PAY ATTENTION the data have some edges which occur many times
		dist[v][u]=dist[u][v]; // two_direction
	}
	//Floyed
	for (int k=1;k<=n;k++)
	{
		for (int i=1;i<=n;i++)
		{
			for (int j=1;j<=n;j++)
			{
				dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);
			}
		}
	}
	//Output
	for (int i=1;i<=n;i++)
	{
		for (int j=1;j<=n;j++)
		{
			printf("%d ",dist[i][j]);
		}
		printf("\n");
	}
	return 0;
}
原文