[PAT]1030 Travel Plan (30 分)-dijkstra

1030 Travel Plan (30 分)

A traveler's map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.

Input Specification:
Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (≤500) is the number of cities (and hence the cities are numbered from 0 to N−1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:

City1 City2 Distance Cost
where the numbers are all integers no more than 500, and are separated by a space.

Output Specification:
For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.

Sample Input:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
Sample Output:
0 2 3 3 40

分析

看到找最短路径的时候就知道是dijkstra
只是这道题在dijkstra的基础上,增加了在路径最短的条件下求最小cost,只需要在dijkstra的基础上增加遇到相等路径时的判断,那个最小的cost,增加一个pre数组记录路径。

                if(dis[v]>map[u][v]+dis[u]){
                    dis[v]=map[u][v]+dis[u];
                    cost[v]=money[u][v]+cost[u];
                    pre[v]=u;
                }else if(dis[v]==map[u][v]+dis[u]){//和dijkstra有区别的地方
                    if(cost[v]>money[u][v]+cost[u]){
                        cost[v]=money[u][v]+cost[u];
                        pre[v]=u;
                    }
                }

AC代码

#include
#include
using namespace std;
int inf = 0x3f3f3f3f;
#define maxn 500
int n,m,st,ed;

int map[maxn][maxn];
int money[maxn][maxn];
int cost[maxn];
int dis[maxn];
int book[maxn];
int pre[maxn];

vector path;
void dijkstra(int x){
    dis[x]=0;
    cost[x]=0;
    for(int i=0;imap[u][v]+dis[u]){
                    dis[v]=map[u][v]+dis[u];
                    cost[v]=money[u][v]+cost[u];
                    pre[v]=u;
                }else if(dis[v]==map[u][v]+dis[u]){
                    if(cost[v]>money[u][v]+cost[u]){
                        cost[v]=money[u][v]+cost[u];
                        pre[v]=u;
                    }
                }
            }
        }
    }
}


int main(){
    cin>>n>>m>>st>>ed;
    for(int i=0;i>a>>b>>c>>d;
        map[a][b]=map[b][a]=c;
        money[a][b]=money[b][a]=d;
    }
    //³õʼ»¯disÊý×é
    for(int i=0;i=0;i--)
    {
        cout<

你可能感兴趣的:([PAT]1030 Travel Plan (30 分)-dijkstra)