旅遊規劃(自己寫的floyd代碼+沒學會的dij算法)
阿新 • • 發佈:2018-03-29
rap truct min mes dijk stdio.h out 城市 weight
有了一張自駕旅遊路線圖,你會知道城市間的高速公路長度、以及該公路要收取的過路費。現在需要你寫一個程序,幫助前來咨詢的遊客找一條出發地和目的地之間的最短路徑。如果有若幹條路徑都是最短的,那麽需要輸出最便宜的一條路徑。
輸入格式:
輸入說明:輸入數據的第1行給出4個正整數N、M、S、D,其中N(2)是城市的個數,順便假設城市的編號為0~(N?1);M是高速公路的條數;S是出發地的城市編號;D是目的地的城市編號。隨後的M行中,每行給出一條高速公路的信息,分別是:城市1、城市2、高速公路長度、收費額,中間用空格分開,數字均為整數且不超過500。輸入保證解的存在。
輸出格式:
在一行裏輸出路徑的長度和收費總額,數字間以空格分隔,輸出結尾不能有多余空格。
輸入樣例:
4 5 0 3 0 1 1 20 1 3 2 30 0 3 4 10 0 2 2 20 2 3 1 20
輸出樣例:
3 40
Floyd代碼
#include<iostream> #include<string> #include<cmath> using namespace std; #define MAX 1e9 struct { int l, s; }a[500][500]; int main() { int N, M, S, D,i,j,k,x,y,ll,ss; cin >> N >> M >> S >> D;for (i = 0; i < N;i++) for (j = 0; j < N; j++) { if (i == j) { a[i][j].l = 0; a[i][j].s = 0; } else { a[i][j].l = MAX; a[i][j].s = MAX; } } while (M--) { cin >> x >> y >> ll >> ss; a[x][y].l= ll; a[y][x].l = ll; a[y][x].s =ss; a[x][y].s = ss; } for (k = 0; k < N;k++) for (i = 0; i < N;i++) for (j = 0; j < N;j++) if (a[i][j].l>a[i][k].l + a[k][j].l || a[i][j].l == a[i][k].l + a[k][j].l&&a[i][j].s>a[i][k].s + a[k][j].s) { a[i][j].l = a[i][k].l+ a[k][j].l; a[i][j].s = a[i][k].s + a[k][j].s; } cout << a[S][D].l << " " << a[S][D].s; }
Floyd算法(唉,天梯賽前學不會了)
#include <stdio.h> #define MAX 100000 typedef struct { int weight; int cost; }graph; int N,M,S,D; graph g[500][500]; int dis[500]; int cost[500]; int flag[500]; void Dijkstra(int v) { int min,i,j,pos; for(i=0;i<N;i++) { if(g[v][i].weight>0 ) { dis[i]=g[v][i].weight; cost[i]=g[v][i].cost; } } flag[v]=1; for(i=0;i<N;i++) { min=MAX; pos=v; for(j=i;j<N;j++) { if(flag[j]!=1 &&dis[j]<min &&dis[j]>0) { min=dis[j]; pos=j; } } flag[pos]=1; for(j=0;j<N;j++) { if(flag[j]!=1&&dis[pos]+g[pos][j].weight<dis[j] &&g[pos][j].weight>0&&dis[j]>0) { dis[j]=dis[pos]+g[pos][j].weight; cost[j]=cost[pos]+g[pos][j].cost; } else if(dis[pos]+g[pos][j].weight==dis[j] &&cost[j]>cost[pos]+g[pos][j].cost) { cost[j]=cost[pos]+g[pos][j].cost; } } } printf("%d %d\n",dis[D],cost[D]); } main() { int a,b,l,c; int i,j; scanf("%d%d%d%d",&N,&M,&S,&D); for(i=0;i<M;i++) { scanf("%d%d%d%d",&a,&b,&l,&c); g[a][b].weight=g[b][a].weight=l; g[a][b].cost=g[b][a].cost=c; } Dijkstra(S); }
旅遊規劃(自己寫的floyd代碼+沒學會的dij算法)