PAT

来源:互联网 发布:php抽奖系统 编辑:程序博客网 时间:2024/06/13 11:06

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 30 1 1 201 3 2 300 3 4 100 2 2 202 3 1 20
Sample Output
0 2 3 3 40

题目有2个要求:
1.求出最短路
2.求出最短路中需要的花费最低的路

解决方法:
1.Dijkstra算法求出最短路,并且记录路径
2.遍历最短路的所有路径,找出花费最少的路
3.输出最短+花费最少的路


#include<iostream>#include<cstdio>#include<vector>#define INF 999999999using namespace std;int a, b, c, d;int N, M, S, D;int e[505][505];int cost[505][505];int dis[505];int vis[505];int mincost = INF;vector<int> path;vector<int> temp;vector<int> pre[505];void dfs(int v){if(v == S){temp.push_back(S);int sum = 0;for(int i = 1; i < temp.size(); i++){int i1 = temp[i-1];int i2 = temp[i];sum += cost[i1][i2];}if(sum < mincost){mincost = sum;path = temp;}temp.pop_back();return ;}temp.push_back(v);for(int i = 0; i < pre[v].size(); i++){dfs(pre[v][i]);}temp.pop_back();}int main(){freopen("input.txt", "r", stdin);while(scanf("%d%d%d%d",&N, &M, &S, &D) != EOF){// initfill(e[0], e[0] + 505 * 505, INF);    fill(dis, dis + 505, INF);    fill(vis, vis + 505, 0);    // inputfor(int i = 0; i < M; i++){scanf("%d%d%d%d",&a, &b, &c, &d);e[a][b] = e[b][a] = c;cost[a][b] = cost[b][a] = d;}// Dijkstradis[S] = 0;for(int i = 0; i < N; i++){int x = -1, minl = INF;for(int j = 0; j < N; j++){if(!vis[j] && dis[j] < minl){x = j;minl = dis[j];}}if(x == -1) break;vis[x] = 1;for(int j = 0; j < N; j++){if(!vis[j] && e[x][j] != INF){if(dis[x] + e[x][j] < dis[j]){dis[j] = dis[x] + e[x][j];pre[j].clear();pre[j].push_back(x);}else if(dis[x] + e[x][j] == dis[j]){pre[j].push_back(x);}}}}//dfsdfs(D);// outputfor(int i = path.size()-1; i >=0; i--){if(i==path.size()-1) printf("%d",path[i]);else printf(" %d",path[i]);}printf(" %d %d\n",dis[D],mincost);}return 0;}




原创粉丝点击