题目
Indeed there are many different tourist routes from our city to Rome. You are supposed to find your clients the route with the least cost while gaining the most happiness.
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive integers N (2≤N≤200), the number of cities, and K, the total number of routes between pairs of cities; followed by the name of the starting city. The next N−1 lines each gives the name of a city and an integer that represents the happiness one can gain from that city, except the starting city. Then K lines follow, each describes a route between two cities in the format City1 City2 Cost. Here the name of a city is a string of 3 capital English letters, and the destination is always ROM which represents Rome.
Output Specification:
For each test case, we are supposed to find the route with the least cost. If such a route is not unique, the one with the maximum happiness will be recommanded. If such a route is still not unique, then we output the one with the maximum average happiness – it is guaranteed by the judge that such a solution exists and is unique.
Hence in the first line of output, you must print 4 numbers: the number of different routes with the least cost, the cost, the happiness, and the average happiness (take the integer part only) of the recommanded route. Then in the next line, you are supposed to print the route in the format City1->City2->…->ROM.
Sample Input:
6 7 HZH
ROM 100
PKN 40
GDN 55
PRS 95
BLN 80
ROM GDN 1
BLN ROM 1
HZH PKN 1
PRS ROM 2
BLN HZH 2
PKN GDN 1
HZH PRS 1
Sample Output:
3 3 195 97
HZH->PRS->ROM
思路
这道题算是此类型中综合性强的经典题目了,需要好好掌握。
简单粗暴的思路就是:Dijkstra + DFS。
首先画出带权无向图,节点的值表示happy,边的值表示cost。将节点按输入顺序编号为0-5,用map存储城市名-序号对应关系,用vector存储序号-城市名对应关系。
问题即转化为求无向带权图的权值最高的最短路径。
用Dijkstra算法求出单源最短路径,保存到数组dist[]中,dist[1](ROM的编号为1)即为到ROM的最短距离。
传统Dijkstra算法中,使用数组pre[]保存每个节点的前趋节点,只记录一条最短路径。为了记录多条最短路径,只需将pre[]数组扩展为二维的pre[][],pre[i][j]表示第i个节点的第j个前趋节点。
例如本题中,得到的pre数组为:
pre[0]:
pre[1]: 4 3 5
pre[2]: 0
pre[3]: 2
pre[4]: 0
pre[5]: 0
根据pre[][]数组,从ROM开始dfs,dfs途中将经过的节点加入到形参path[]中,将当前happy值的和累计到形参h中。
搜索到序号为0的节点(起点)时停止搜索,并计路径数量+1。
- 若得到的happy值更大,则将该条路径设为最优路径minPath[];
- 若happy值相等,则取path和minPath中节点个数较少的那条(平均值 = 总happy值 / 节点数),即是平均值较大的。
(注意DFS搜索时,无需用visited[]标记未访问节点,因为是允许某节点被访问多次的,否则测试点2会报错)
代码
#include <iostream>
#include <vector>
#include <climits>
#include <unordered_map>
using namespace std;
unordered_map<string, int> mp; //城市名-序号
vector<string> mp1; //序号-城市名
vector<int> happy; //快乐值
vector<int> minPath;
int maxHappy = 0;
int pathCount = 0;
void dfs(