首页 > 其他分享 >PAT Advanced 1030 Travel Plan(30)

PAT Advanced 1030 Travel Plan(30)

时间:2022-08-30 17:56:40浏览次数:50  
标签:Cost PAT min Travel 30 cost path 500 dis

题目描述:

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

算法描述:DFS vector

题目大意:

给出n个城市,m个邻接边,起始点,终点,m个邻接边的具体信息。求起点到终点的最短路径最短距离和花费,要求首先路径最短,其次花费最少,要输出完整路径

#include<iostream>
#include<vector>
using namespace std;

int n, m, s, d, Dis[500][500], Cost[500][500], min_dis[500], min_cost[500];
//N为城市,M为路数,S开头,D结尾
vector<int> v[500], path, final_path;

void dfs(int cur, int curdis, int curcost)
{
	if (curdis>min_dis[cur] || (curdis == min_dis[cur] && curcost>min_cost[cur]))return;
	path.push_back(cur);
	if (curdis<min_dis[cur] || (curdis == min_dis[cur] && curcost<min_cost[cur])) 
    {
		min_dis[cur] = curdis;
		min_cost[cur] = curcost;
	}
	if (cur == d) 
		final_path = path;

	else 
    {
		for (int i = 0; i<v[cur].size(); i++) {
			dfs(v[cur][i], curdis + Dis[cur][v[cur][i]], curcost + Cost[cur][v[cur][i]]);
		}
	}
	path.pop_back();
}

int main()
{
	int i, j, k, dis, cost;
	cin >> n >> m >> s >> d;
	for (i = 0 ; i < m ; i ++) {
		cin >> j >> k >> dis >> cost;
        
		if (!Dis[j][k] || dis < Dis[j][k]) 
			Dis[j][k] = Dis[k][j] = dis;
		if (!Cost[j][k] || cost < Cost[j][k])
			Cost[j][k] = Cost[k][j] = cost;
        
		v[j].push_back(k);
		v[k].push_back(j);
	}
	for(int i = 0 ; i < n ; i ++)
    {
        min_dis[i] = 1000000;
        min_cost[i] = 1000000;
    }
	dfs(s, 0, 0);
	for (i = 0; i<final_path.size(); i++) 
		cout << final_path[i] << ' ';
	cout << min_dis[d] << ' ' << min_cost[d];
}

标签:Cost,PAT,min,Travel,30,cost,path,500,dis
From: https://www.cnblogs.com/yztozju/p/16640279.html

相关文章