#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define INF 0x7f
#define maxn 200
int dis[maxn][maxn];
int path[maxn][maxn];
int n;
void floyd()
{
int i,j,k;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i!=j&&dis[i][j]<INF) path[i][j]=i;
else path[i][j]=-1;
}
}
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(k==i||k==j) continue;
if(dis[i][j]>dis[i][k]+dis[k][j])
{
dis[i][j]=dis[i][k]+dis[k][j];
path[i][j]=path[k][j];
}
}
}
}
}
int main()
{
int i,j,from,to,val;
cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
dis[i][j]=INF;
}
}
while(cin>>from>>to>>val)
{
if(from==-1&&to==-1&&val==-1) break;
if(dis[from][to]>val)
dis[from][to]=dis[from][to]=val;
}
floyd();
int shorest[maxn];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j) continue;
printf("%d=>%d\t%d\t",i,j,dis[i][j]);
memset(shorest,0,sizeof(shorest));
int k=0;
shorest[k]=j;
while(path[i][shorest[k]]!=i)
{
k++;
shorest[k]=path[i][shorest[k-1]];
}
k++;
shorest[k]=i;
for(int t=k;t>0;t--)
printf("%d->",shorest[t]);
printf("%d\n",shorest[0]);
}
}
return 0;
}
Floyd模板
最新推荐文章于 2022-11-18 23:25:12 发布