Floyd算法实现–多源最短路径O(n^3)
//int d[i][j]//i到j的最路径
//int path[i][j]//i到j的最短路径上j的前一个顶点序号
//初始化
for(int i=1;i<=n;i++)
{
for(int j=1;j<=1;j++)
{
d[i][j]=endge[i][j];//i到j的最短路径初始化为邻接矩阵
if(i!=j&&d[i][j]<inf)//判断i到j是否有边
{
path[i][j]=i;//有边则代表j的前一个结点为i
}
else
path[i][j]=-1;//无路
}
}
//递推
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(d[i][k]+d[k][j]<d[i][j])//松弛
{
d[i][j]=d[i][k]+d[k][j];
path[i][j]=path[k][j];//j的前一个顶点更新为k->j时j的前顶点
}
}
}
//如何得到i-j的一条最短路
k=path[i][j];
...
k=path[i][k];
#include<iostream>
using namespace std;
int mapp[1000][1000],path[1000][1000];
int m,n,x,y;
const int inf=1e9;
int floyd(){
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(mapp[i][j]>mapp[i][k]+mapp[k][j]){
mapp[i][j]=mapp[i][k]+mapp[k][j];
path[i][j]=path[i][k];
}
}
}
}
}
int main(){
cin>>m>>n>>x>>y;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j)
mapp[i][j]=0;
else
mapp[i][j]=inf;
}
}
int a,b,c;
for(int i=1;i<=m;i++){
cin>>a>>b>>c;
mapp[b][a]=mapp[a][b]=mapp[a][b]>c?c:mapp[a][b];
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(mapp[i][j]!=inf){
path[i][j]=j;
}
else
path[i][j]=-1;
}
}
floyd();
cout<<mapp[x][y]<<endl;
int k=path[x][y];
cout<<x<<"->";
while(k!=y){
cout<<k<<"->";
k=path[k][y];
}
cout<<y;
return 0;
}
...
HDU 1690
题目链接
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
#define min(a,b) (a)>(b)?(b):(a)
#define inf 110000000000
typedef long long ll;
ll p[110],map[110][110];
void floyd(int n)
{
for(int k=1;k<=n;k++)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
map[i][j]=min(map[i][j],map[i][k]+map[k][j]);
}
}
}
}
int main()
{
int t,c=1;
scanf("%d",&t);
while(t--)
{
ll L1,L2,L3,L4,c1,c2,c3,c4;
scanf("%I64d%I64d%I64d%I64d%I64d%I64d%I64d%I64d",&L1,&L2,&L3,&L4,&c1,&c2,&c3,&c4) ;
int m,n;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%I64d",&p[i]);
}
for(int i=1;i<=n;i++)
{
map[i][i]=0;
for(int j=1;j<i;j++)
{
ll dis=abs(p[i]-p[j]);
if(dis<=L1)
{
map[i][j]=map[j][i]=c1;
}
else if(dis>L1&&dis<=L2)
{
map[i][j]=map[j][i]=c2;
}
else if(dis>L2&&dis<=L3)
{
map[i][j]=map[j][i]=c3;
}
else if(dis>L3&&dis<=L4)
{
map[i][j]=map[j][i]=c4;
}
else{
map[i][j]=map[j][i]=inf;
}
}
}
floyd(n);
printf("Case %d:\n",c++);
for(int i=0;i<m;i++)
{
int s, t;
scanf("%d%d",&s,&t);
if(map[s][t]>=inf)
{
printf("Station %d and station %d are not attainable.\n",s,t) ;
}
else
{
printf("The minimum cost between station %d and station %d is %I64d.\n",s,t,map[s][t]) ;
}
}
}
return 0;
}