07-图6 旅游规划 (25分)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 505
#define INF 100005

typedef struct ENode* Edge;
struct ENode {
    int v1, v2;
    int w1, w2;
};

typedef struct GNode* Graph;
struct GNode {
    int Nv, Ne;
    int Data1[MAXN][MAXN];
    int Data2[MAXN][MAXN];
};

Graph CreateGraph(int n, int m) {
    int i, j;
    Graph G = (Graph)malloc(sizeof(struct GNode));
    G->Nv = n;
    G->Ne = m;
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++) {
            G->Data1[i][j] = G->Data2[i][j] = INF;
        }
    }
    return G;
}

void InsertEdge(Graph G, Edge E) {
    G->Data1[E->v1][E->v2] = G->Data1[E->v2][E->v1] = E->w1;
    G->Data2[E->v1][E->v2] = G->Data2[E->v2][E->v1] = E->w2;
}

Graph BuildGraph(int n, int m) {
    int v;
    Graph G;
    Edge E = (Edge)malloc(sizeof(struct ENode));
    G = CreateGraph(n, m);
    for(v = 0; v < G->Ne; v++) {
        scanf("%d%d%d%d", &E->v1, &E->v2, &E->w1, &E->w2);
        InsertEdge(G, E);
    }
    return G;
}
//查找未收入点集中的点中距离最小的点
int FindMinDist(Graph G, int dist[], int vertex[]) {
    int v, MinDist = INF, Minv = 0;
    for(v = 0; v < G->Nv; v++) {
        if(!vertex[v] && dist[v] < MinDist) {
            MinDist = dist[v];
            Minv = v;
        }
    }
    if(MinDist != INF) return Minv;
    else return -1;
}

void Dijkstra(Graph G, int dist[], int path[], int s, int cost[]) {
    int vertex[MAXN];
    int v, w;
    for(v = 0; v < G->Nv; v++) {
        if(G->Data1[s][v]) path[v] = s;
        else path[v] = -1;
        dist[v] = G->Data1[s][v];
        cost[v] = G->Data2[s][v];
        vertex[v] = 0;
    }
    vertex[s] = 1;
    dist[v] = 0;
    for( ; ; ) {
        v = FindMinDist(G, dist, vertex);
        if(v == -1) break;
        vertex[v] = 1;
        for(w = 0; w < G->Nv; w++) {
            if(!vertex[w] && dist[w] > dist[v] + G->Data1[v][w]) {
                dist[w] = dist[v] + G->Data1[v][w];
                path[w] = v;
                cost[w] = cost[v] + G->Data2[v][w];
            }
            else if(!vertex[w] && dist[w] == dist[v] + G->Data1[v][w]) {
                if(cost[w] > cost[v] + G->Data2[v][w]) {
                    path[w] = v;
                    cost[w] = cost[v] + G->Data2[v][w];
                }
            }
        }
    }
}

int main() {
    int n, m, s, d;
    int path[MAXN], dist[MAXN], cost[MAXN];
    Graph G;
    scanf("%d%d%d%d", &n, &m, &s, &d);
    G = BuildGraph(n, m);
    Dijkstra(G, dist, path, s, cost);
    printf("%d %d\n", dist[d], cost[d]);
    return 0;
}

/*
Dijkstra算法。建图时初始化边权INF。
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值