![Minimum Transport Cost HDU1385(路径打印) Minimum Transport Cost HDU1385(路径打印)](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
最短路的路径打印问题 同时路径要是最小字典序
字典序用floyd方便很多
学会了两种打印路径的方法!!!
#include <stdio.h>
#include <string.h>
#define N 110
#define INF 1000000000
int d[N][N],path[N][N],c[N];
int n,cost;
int s,t; void input()
{
int i,j,w;
for(i=; i<=n; i++)
for(j=; j<=n; j++)
{
scanf("%d",&d[i][j]);
if(d[i][j]==-) d[i][j]=INF;
path[i][j]=j;
}
for(i=; i<=n; i++)
scanf("%d",&c[i]); return ;
} void Floy()
{
int i,j,k; for(k=; k<=n; k++) //中转站k
for(i=; i<=n; i++) //起点和终点i,j
for(j=; j<=n; j++)
{
if( d[i][j] > d[i][k]+d[k][j]+c[k] )
{
d[i][j]=d[i][k]+d[k][j]+c[k];
path[i][j]=path[i][k];
} else if( d[i][j] == d[i][k]+d[k][j]+c[k] )
{
if( path[i][j] > path[i][k])
{
d[i][j]=d[i][k]+d[k][j]+c[k];
path[i][j]=path[i][k];
}
} }
return ;
} void print_path(int u , int v) //u是起点v是终点
{
int k;
if(u==v)
{
printf("%d",v);
return ;
}
k=path[u][v];
printf("%d-->",u);
print_path(k,v);
}
int main()
{
while(scanf("%d",&n)!=EOF && n)
{
input();
Floy(); while(scanf("%d%d",&s,&t))
{
if( s==- && t==-) break;
cost=d[s][t];
if(s==t) //起点和终点相同
{
printf("From %d to %d :\n",s,t);
printf("Path: %d\n",s);
printf("Total cost : %d\n\n",cost);
continue;
}
printf("From %d to %d :\n",s,t);
printf("Path: ");
print_path(s,t);
printf("\n");
printf("Total cost : %d\n\n",cost);
}
}
return ;
}
dijkstra实现
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=;
const int inf=;
int pos=;
int G[maxn][maxn],d[maxn],c[maxn],pre[maxn];
bool vis[maxn];
int n,st,ed;
void dfs(int u,char *s)
{
if(u==st) return ;
dfs(pre[u],s);
s[pos++]=u+'';
}
bool cmp(int u,int v)
{
char s1[maxn],s2[maxn];
pos=;
dfs(u,s1);
s1[pos]='\0';
pos=;
dfs(v,s2);
s2[pos]='\0';
if(strcmp(s1,s2)==) return true;
return false;
}
void dijkstra(int st)
{
fill(d,d+maxn,inf);
for(int i=;i<=n;i++) pre[i]=i;
d[st]=;
for(int i=;i<=n;i++)
{
int u=-,MIN=inf;
for(int j=;j<=n;j++)
{
if(!vis[j]&&d[j]<MIN)
{
MIN=d[j];
u=j;
}
}
if(u==-) return ;
vis[u]=true;
for(int v=;v<=n;v++)
{
if(G[u][v]!=inf&&vis[v]==false&&G[u][v]+d[u]+c[u]<d[v])
{
d[v]=G[u][v]+d[u]+c[u];
pre[v]=u;
}
else
{
if(G[u][v]+d[u]+c[u]==d[v]&&cmp(v,u))
pre[v]=u;
}
} }
} void show(int v)
{
if(v==st)
{
cout<<v;
return ;
}
show(pre[v]);
cout<<"-->"<<v;
}
int main()
{
while (cin>>n&&n!=) {
memset(vis,false,sizeof(vis));
//fill(G[0],G[0]+maxn*maxn,inf);
for(int i=;i<=n;i++)
{
for(int j=;j<=n;j++)
{
cin>>G[i][j];
if(G[i][j]==-)
G[i][j]=inf;
}
}
for(int i=;i<=n;i++)
cin>>c[i];
while (cin>>st>>ed)
{
memset(vis,false,sizeof(vis));
if(st==-&&ed==-) break;
if(st==ed) {
printf("From %d to %d :\n",st,ed);
printf("Path: %d\n",st);
printf("Total cost : 0\n\n"); }
else{
dijkstra(st);
printf("From %d to %d :\n",st,ed);
printf("Path: ");
show(ed);
cout<<endl;
printf("Total cost : %d\n",d[ed]-c[st]);
cout<<endl;
}
}
}
}