7-9 旅遊規劃

有了一張自駕旅遊路線圖,你會知道城市間的高速公路長度、以及該公路要收取的過路費。現在需要你寫一個程序,幫助前來諮詢的遊客找一條出發地和目的地之間的最短路徑。如果有若干條路徑都是最短的,那麼需要輸出最便宜的一條路徑。

輸入格式:

輸入說明:輸入數據的第1行給出4個正整數NNNMMMSSSDDD,其中NNN2≤N≤5002\le N\le 5002N500)是城市的個數,順便假設城市的編號爲0~(N−1N-1N1);MMM是高速公路的條數;SSS是出發地的城市編號;DDD是目的地的城市編號。隨後的MMM行中,每行給出一條高速公路的信息,分別是:城市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

參考代碼:

#include <stdio.h>
#include <stdlib.h>
#define MaxNum 500
#define INFINITY 65533
typedef int Vertex;
typedef int Weight;
/*Dijkstral算法變形*/
struct GNode{
    int Nv;
    int Ne;
    Weight G1[MaxNum][MaxNum];
    Weight G2[MaxNum][MaxNum];//兩個權重
};
typedef struct GNode *Graph;
struct ENode{
    Vertex V1;
    Vertex V2;
    Weight W1;//距離
    Weight W2;//收費
};
typedef struct ENode *Edge;

Vertex FindMin(Graph G, int dist[], int check[])
{
    Vertex MinV;
    int Mindist = INFINITY;
    for (int i = 0; i < G->Nv; i++){
        if (check[i] != 1 && dist[i] < Mindist){
            Mindist = dist[i];
            MinV = i;
        }
    }
    if (Mindist < INFINITY)
        return MinV;
    else
        return -1;
}

void Dijkstra(Graph G, Vertex S, int dist[], int cost[])
//起點S,終點D
{
    Vertex V;
    int check[MaxNum] = {0,};
    for (int i = 0; i < G->Nv; i++){
        dist[i] = G->G1[S][i];
        cost[i] = G->G2[S][i];
    }
    check[S] = 1;
    while (1){
        V = FindMin(G, dist, check);
        if (V == -1)
            break;
        check[V] = 1;
        for (int i = 0; i < G->Nv; i++){
            if (check[i] == 0 && G->G1[V][i] < INFINITY){
                if (dist[V] + G->G1[V][i] < dist[i]){
                    dist[i] = dist[V] + G->G1[V][i];
                    cost[i] = cost[V] + G->G2[V][i];
                }
                else if (dist[V] + G->G1[V][i] == dist[i])
                    if (cost[V] + G->G2[V][i] < cost[i])
                        cost[i] = cost[V] + G->G2[V][i];
            }
        }
    }
    
}

int main(int argc, char const *argv[])
{
    Graph G = (Graph)malloc(sizeof(struct GNode));
    Edge E = (Edge)malloc(sizeof(struct ENode));
    int N, M;
    Vertex S, D;//S-->起點  D-->終點
    scanf("%d %d %d %d\n", &N, &M, &S, &D);
    G->Nv = N;
    G->Ne = M;
    //初始化圖
    for (int i = 0; i < G->Nv; i++ )
        for (int j = 0; j < G->Nv; j++){
            G->G1[i][j] = INFINITY;
            G->G2[i][j] = INFINITY;
        }
    //無向網圖插入邊
    for (int i = 0; i < G->Ne; i++){
        scanf("%d %d %d %d", &E->V1, &E->V2, &E->W1, &E->W2);
        G->G1[E->V1][E->V2] = E->W1;
        G->G1[E->V2][E->V1] = E->W1;
        G->G2[E->V1][E->V2] = E->W2;
        G->G2[E->V2][E->V1] = E->W2;
    }
    //Dijstral算法(指定終點)
    int dist[MaxNum], cost[MaxNum];
    Dijkstra(G, S, dist, cost);
    printf("%d %d", dist[D], cost[D]);
    system("pause");
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章