图的最短路径问题-07-图6 旅游规划

来源:互联网 发布:希腊经济知乎 编辑:程序博客网 时间:2024/06/07 16:43
  • 题目
    07-图6 旅游规划 (25分)
  • 分析
    这道题明显是个单源无向图的最短路径问题,但是这儿注意的是有两个权重:一是距离,二是收费。可以用Dijkstra算法来求解。当距离相等时按照收费来更新最短路。
    伪码描述:
//dist[i]表示结点i到源点S的距离//cost[i]表示结点i到源点S的收费void Dijkstra(源点S){    while(1){        V = 未被收录的结点中dist最小者;        if(这样的V不存在)   break;        collected[V] = true;        for(V的每个邻接点W){            if(!collected[W]){                if(dist[V]+graph[V][W] < dist[W]){                    dist[W] = dist[V] + graph[V][W];                    cost[W] = cost[V] + money[V][W];                }else if(dist[V]+graph[V][W] == dist[W] && cost[W] > cost[V] + money[V][W]){                    cost[W] = cost[V] + money[V][W];                }            }        }    }}
  • 代码
#include<iostream>using namespace std;const int INF = 123456;const int MAXN = 500;int N, M, S, D;int dist[MAXN];     //dist[i]表示i到S的距离int cost[MAXN]; //cost[i]表示i到S的费用bool visited[MAXN] = {false};int graph[MAXN][MAXN];int money[MAXN][MAXN];void Dijkstra(int s){    int i,short1,v0;    visited[s] = true;    while(1)    {        short1  = INF;        v0 = -1;        for(i=0; i<N; i++){            if(!visited[i]){                if(dist[i] < short1){                    v0 = i;                    short1 = dist[i];                }            }        }        if(v0 <0)   break;        visited[v0] = true;        for(i=0; i<N; i++){            if(!visited[i]){                if(graph[i][v0]+dist[v0]<dist[i]){                    dist[i] = dist[v0] + graph[i][v0];                    cost[i] = cost[v0] + money[i][v0];                }else if(dist[v0]+graph[i][v0] == dist[i] && cost[v0] + money[i][v0]<cost[i]){                    cost[i] = cost[v0] + money[i][v0];                }            }        }    } } int main(){    #ifndef ONLINE_JUDGE    freopen("journey.txt", "r", stdin);    #endif    scanf("%d%d%d%d", &N, &M, &S, &D);    int i, j;    //构造图     for(i=0; i<N; i++){        for(j=0; j<N; j++){            if(i == j){                graph[i][j] = 0;                money[i][j] = 0;            }else{                graph[i][j] = INF;                money[i][j] = INF;            }        }    }    //printf("aaa\n");    int x, y, length, money1;    for(i=0; i<M; i++){        scanf("%d%d%d%d", &x, &y, &length, &money1);        graph[x][y] = graph[y][x] = length;        money[x][y] = money[y][x] = money1;     }    //初始化dist和cost    for(i=0; i<N; i++){        dist[i] = graph[S][i];        cost[i] = money[S][i];    }     Dijkstra(S);    printf("%d %d\n", dist[D], cost[D]);    return 0;}
原创粉丝点击