PAT A 1087 All Roads Lead to Rome (30 分)

一、思路

单源最短路径问题。

直接使用map存储数据求解担心会有超时问题,所以建立0~N - 1和城市缩写的映射关系,用整型城市索引处理。

基于Dijkstra算法的路径选择:
若从点v去j代价更低:更新j路径前驱为v;
若从点v去j代价相同:
1、更新路径条数:n_path[j] += n_path[v],若写成n_path[j]++会导致测试点2答案错误。
2、路过v点的路线,幸福总量sum[]更大,更换为路过v点的路径。
2、幸福总量相同,但经过v点的路线上路过城市cnt[]少,即相当于平均幸福更大,更换为路过v点的路径。

二、代码

#include 
#include 
#include 
#include 
using namespace std;
#define INF 0x7FFFFFFF
int main()
{
	int N, K, D;
	string str, v1, v2;
	cin >> N >> K >> str;
	vector<vector<int>> G(N, vector<int>(N, INF));
	vector<int> path(N, -1), cnt_path(N), cnt_node(N, 0), dist(N, INF), vset(N, 0), hap(N, 0), val(N, 0);
	vector<string> city(N), ans;
	map<string, int> index;
	city[0] = str;
	cnt_path[0] = 1;
	dist[0] = 0;
	for( int i = 1; i < N; ++i )
	{
		cin >> city[i] >> val[i];
		index[city[i]] = i;
		if( city[i] == "ROM" )
			D = i;
	}
	for( int i = 0, d; i < K; ++i )
	{
		cin >> v1 >> v2 >> d;
		G[index[v1]][index[v2]] = G[index[v2]][index[v1]] = d;
	}
	for( int i = 0, v, Min; i < N; ++i )
	{
		Min = INF;
		for( int j = 0; j < N; ++j )
			if( !vset[j] && dist[j] < Min )
			{
				v = j;
				Min = dist[j];
			}
		if( Min == INF )
			break;
		vset[v] = 1;
		for( int j = 0; j < N; ++j )
			if( G[v][j] != INF )
			{
				if( dist[v] + G[v][j] < dist[j] )
				{
					dist[j] = dist[v] + G[v][j];
					cnt_node[j] = cnt_node[v] + 1;
					cnt_path[j] = cnt_path[v];
					hap[j] = hap[v] + val[j];
					path[j] = v;
				}
				else if( dist[v] + G[v][j] == dist[j] )
				{
					cnt_path[j] += cnt_path[v];
					if( hap[v] + val[j] > hap[j] || ( hap[v] + val[j] == hap[j] && cnt_node[v] + 1 < cnt_node[j] ) )
					{
						hap[j] = hap[v] + val[j];
						cnt_node[j] = cnt_node[v] + 1;
						path[j] = v;
					}
				}
			}
	}
	cout << cnt_path[D] << " " << dist[D] << " " << hap[D] << " " << (hap[D] / cnt_node[D]) << endl;
	for( int i = D; i != -1; i = path[i] )
		ans.push_back(city[i]);
	for( int i = ans.size() - 1; i >= 0; --i )
	{
		cout << ans[i];
		if( i )
			cout << "->";
	}
}

你可能感兴趣的:(PAT,A,PAT,PAT,A)