1. 程式人生 > 其它 >7-16 春遊

7-16 春遊

技術標籤:演算法c語言程式設計

7-16 春遊 (25分)
春天陽光燦爛,小宋突然心血來潮想騎自行車去學校外面玩,但是到達目的地的路線不止一條,他想盡快的到達目的地,又能不需要騎太遠的路, 你能幫助他嗎?

輸入格式:
輸入包含一個測試資料,第一行有三個整數n(2 <= n <= 1000),途中可能經過的地點的個數,地點編號1~n;m(1 <= m <= 10000),為路徑的條數;d(2 <= d <= n),目的地編號;其中學校為起點,預設為1。接下來m行: x y time dist , x y表示地點x,y是可以相互到達的,time,dist分別表示x到y或y到x的時間,距離。

輸出格式:
按如下格式輸出“花費的時間+空格+要騎的距離+空格+從學校到達目的地的路徑”,路徑中的兩個地點之間以箭頭(->)分隔。(具體見輸出樣例)

輸入樣例:
在這裡給出一組輸入。例如:

7 8 7
1 2 1 1
1 3 1 1
2 4 1 2
3 4 1 1
4 5 1 2
4 6 1 1
5 7 1 1
6 7 2 1

輸出樣例:
在這裡給出相應的輸出。例如:

4 5 1->3->4->5->7
#include<stdio.h>
#include<string.h>
#include<iostream>
#include
<algorithm>
using namespace std; #define INF 0x3f3f3f3f int n; int tu[1010][1010],len[1010][1010]; int tim[1010],dist[1010]; int vist[1010],path[1010],f[1010]; void dijkstra() { int i,j; while(1) { int minn=INF,x=-1; for(i=1; i<n+1; i++) { if(vist[i]!=1&&tim[i]<minn) { minn=tim[i]
; x=i; } } if(x==-1) break; vist[x]=1; for(i=1; i<n+1; i++) { if(vist[i]||!tu[x][i]) continue; if(tim[i]>tim[x]+tu[x][i]) { tim[i]=tim[x]+tu[x][i]; dist[i]=dist[x]+len[x][i]; path[i]=x; } else if(tim[i]==tim[x]+tu[x][i]) { if(dist[i]>dist[x]+len[x][i]) { dist[i]=dist[x]+len[x][i]; path[i]=x; } } } } } int main() { int i,j,m,end; scanf("%d%d%d",&n,&m,&end); //cin>>n>>m>>end; while(m--) { int a,b,c,d; scanf("%d%d%d%d",&a,&b,&c,&d); //cin>>a>>b>>c>>d; tu[a][b]=tu[b][a]=c; len[a][b]=len[b][a]=d; } /*fill(tim,tim+1005,INF); fill(dist,dist+1005,INF); fill(path,path+1005,-1);*/ memset(tim,INF,sizeof(tim)); memset(dist,INF,sizeof(dist)); memset(path,-1,sizeof(path)); tim[1]=0; dist[1]=0; dijkstra(); printf("%d %d ",tim[end],dist[end]); //cout<<tim[end]<<" "<<dist[end]<<" "; int k=1; f[0]=end; while(path[end]!=-1) { end=path[end]; f[k++]=end; } for(i=k-1;i>=1;i--) printf("%d->",f[i]); printf("%d",f[0]); }