最短路径讲解
1261:【例9.5】城市交通路网
#pragma GCC optimize(2)//开O2,不用管,建议慎用(NOIP不准用)
#include<cstdio>
#include<string>
#include<iostream>
#include<cstring>
#include<stdlib.h>
using namespace std;
const int maxn=101;
const int inf=0x7f7f7f7f;
int n;
int map[maxn][maxn];
bool vis[maxn];
int dis[maxn];
int pre[maxn];
int f=1;
int read()
{
int x=0,f=1;char c=getchar();
while(!isdigit(c)){
if(c=='-')
f=-1;
c=getchar();
}
while(isdigit(c))
{
x=x*10+c-'0';
c=getchar();
}
return x*f;
}
void print(int x)//经典的输出函数
{
if(x==0)return;
else {
print(pre[x]);
printf("%d ",x+1);
}
}
void work()
{
n=read();
memset(dis,inf,sizeof(dis));
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
map[i][j]=read();
if(map[i][j]==0)
map[i][j]=inf;
else if(i==0)
dis[j]=map[i][j];
}
dis[0]=0;
//printf("minlong=%d
",dis[n-1]);
//printf("%d",dis[4]);
for(int i=0;i<n;i++)
{
int minn=inf,x=0;
for (int j=0;j<n;j++)
{
if(!vis[j]&&minn>dis[j])
minn=dis[j],x=j;
}
vis[x]=1;
//printf("%d
",x);
for (int j=0;j<n;j++)
if(map[x][j]+dis[x]<dis[j])
{
pre[j]=x; //我竟然卡了输出
dis[j]=map[x][j]+dis[x];
}
}
printf("minlong=%d
",dis[n-1]);
printf("1 ");
print(n-1);
}
int main()
{
work();
return 0;
}