最短路径+Dijkstra+打印路径

甘道夫的最短路径
本文介绍了一个基于Dijkstra算法实现的最短路径问题解决方案。魔法师甘道夫需要找到从A城到B城的最短路径,通过解析输入的城市间连接及距离,程序能够输出最短路径长度及其经过的城市序列。

2763--最短路径

Description

魔法师甘道夫家住A城,他收到B城国王的邀请参加一个重要会议,已知A城到B城中间有n-2个城城市,为了尽快达到目的地,甘道夫通过水晶球了解到A城到B城的地图,图上显示了n个城镇之间的连接(仅仅考虑单向的路,即考虑第i个城只考虑与后面城的连接的路)和距离。 
请你编个程序找出最短的路径 

Input

第一行 n 表示从A到B的n个城市 1 表示城A n表示城B 
第二行到第n+1 行 每行 n个数字 
(第i+1行,表示 第i个城市与其他城市之间的连接关系 0 表示不连接 其他数字表示连接的距离 )

Output

第一行 一个数字 最短距离 
第二行 n个用空格间隔的整数 表示所选的线路

Sample Input

7
0 3 5 0 0 0 0
0 0 0 7 8 6 0
0 0 0 0 4 5 0
0 0 0 0 0 0 4
0 0 0 0 0 0 7
0 0 0 0 0 0 6
0 0 0 0 0 0 0

Sample Output

14
1 2 4 7
#include <cstdio>
#include <cstring>
#include <algorithm>
const int N = 1100;  
const int inf = 99999999;  
int cost[N][N],path[N];  
int d[N],n,y,a[N];  
bool deleted[N];  
void Shortest_path()
{	 
	for(int i=1;i<=n;i++)
    {
        d[i]=inf;
        deleted[i]=false;
    }
    d[1]=0;
    for(int i=1;i<=n;i++)
        if(cost[1][i])
        {
            d[i]=cost[1][i];
        }
		deleted[1]=true;
		a[y=0]=1;
		while(true)
		{
			int min=inf,x;
			for(int i=1;i<=n;i++)  
				if(!deleted[i]&&d[i]<min)  
				{
					min=d[i];
					x=i;
				}	   
				if(min==inf)   break;
				
				//printf("%d\n",x);
				
				deleted[x]=true;
				for(int i=1;i<=n;i++)  if(!deleted[i]&&cost[x][i])
				{
					if(d[x]+cost[x][i]<d[i])
					{
						d[i]=d[x]+cost[x][i];    a[i]=x;  	
					}
					
				}            
		}
		printf("%d\n",d[n]);
		int k=0;
		path[k]=n;
		while(path[k]!=1)
		{
			k++;path[k]=a[path[k-1]];
		}
		for(int i=k;i>=0;i--)
			if(path[i])
				printf("%d ",path[i]);   
}
int main() 
{
    int c,i,j;
    while(scanf("%d",&n),n)
    {
		memset(cost,0,sizeof(cost));
        for( i=1;i<=n;i++)
			for(j=1;j<=n;j++)
			{
				scanf("%d",&c);
				if(c>0)
				{
					cost[i][j]=c;
					cost[j][i]=c;
				}
				
			}
			Shortest_path();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值