PAT 1087. All Roads Lead to Rome: BFS(Dijkstra) + DFS


BFS and DFS: BFS adopts Dijkstra to get minimum cost for each node (shortest path). DFS reconstructs the complete path and pick the one with the most happiness. So I consider this problem is a good one which combines BFS and DFS in a single place.

All Roads Lead to Rome Problem:

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 recommended. 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 recommended 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

Sample Output:

3 3 195 97

All Roads Lead to Rome Analysis:

As I already briefly mentioned, the algorithm involve two parts BFS and DFS:

1) use BFS(Dijkstra) to find the shortest path for all cities

2) by the parents node we record during dijkstra, we use dfs to reconstruct all the path(s) with the minimum cost

3) we pick the one among all the paths which has the maximum happiness or average happiness.

The following source code is accepted by the PAT OJ:

class mycomparison
	mycomparison() {}
	~mycomparison() {}
	bool operator() (const std::pair<int, int>& lhs,
					 const std::pair<int, int>& rhs) const
		return lhs.first > rhs.first;

int N, K;
int adj[205][205];
std::string names[205];
int happiness[205];

void dfs(std::vector<std::vector<int> > &paths, std::vector<int> &path, int node, std::vector<int> parents[]) {
		if (parents[node].empty()) {
			return ;
		for (auto itr = parents[node].begin(); itr != parents[node].end(); ++itr) {
			dfs(paths, path, *itr, parents);

void dij(int s, int t) {
	bool visited[205];
	std::vector<int> parents[205];
	std::pair<int, int> nodes[205];

	for (int i = 0; i < N; ++i) {
		nodes[i].first = INT_MAX;
		nodes[i].second = i;
		visited[i] = false;

	std::priority_queue< std::pair<int, int>, std::vector<std::pair<int, int> >, mycomparison> q;
	nodes[s].first = 0;
	while (!q.empty()) {
		std::pair<int, int> curr =; q.pop();
		if (visited[curr.second]) continue;
		visited[curr.second] = true;
		for (int i = 0; i < N; ++i) {
			int dist = adj[curr.second][i];
			if (dist != INT_MAX && !visited[i]) {
				if (curr.first + dist == nodes[i].first) {
				else if (curr.first + dist <  nodes[i].first) {
					nodes[i].first = curr.first + dist;
				else ;
	std::vector<int> vecPath;
	std::vector<std::vector<int> > vecPaths;
	dfs(vecPaths, vecPath, t, parents);

	int nMaxTotalHappiness = 0;
	double dMaxAvgHappiness = 0.0;
	int nWhichPath = -1;

	for (int i = 0; i < vecPaths.size(); ++i) {
		int happy = 0;
		for (auto itr = vecPaths[i].begin(); itr != vecPaths[i].end(); ++itr) {
			happy += happiness[*itr];
		double avg = happy * 1.0 / (vecPaths[i].size() - 1);
		if (happy > nMaxTotalHappiness) {
			nWhichPath = i;
			nMaxTotalHappiness = happy;
			nMaxAvgHappiness = avg;
		else if (happy == nMaxTotalHappiness) {
			if (avg > nMaxAvgHappiness) {
				nMaxAvgHappiness = avg;
				nWhichPath = i;
		else ;
	std::cout << vecPaths.size() << ' ' << nodes[t].first  << ' '
	          << nMaxTotalHappiness << ' ' << (int)nMaxAvgHappiness << std::endl;
	std::cout << names[s];
	for (int i = vecPaths[nWhichPath].size() - 2; i >= 0; --i) {
		std::cout << "->" << names[vecPaths[nWhichPath][i]];
	std::cout << std::endl;

int main() {
	std::unordered_map<std::string, int> name2id;
	std::cin >> N >> K >> names[0];
	happiness[0] = 0;
	for (int i = 1; i < N; ++i) {
		std::cin >> names[i] >> happiness[i];
	for (int i = 0; i < N; ++i) name2id[names[i]] = i;
	for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) adj[i][j] = INT_MAX;

	std::string city1, city2;
	int cost;
	for (int i = 0; i < K; ++i) {
		std::cin >> city1 >> city2 >> cost;
		int id1 = name2id[city1], id2 = name2id[city2];
		adj[id1][id2] = adj[id2][id1] = cost;
	dij(name2id[names[0]], name2id["ROM"]);
	return 0;


To summarize, this problem involves BFS and DFS: BFS adopts Dijkstra to get minimum cost for each node (shortest path). DFS reconstructs the complete path and pick the one with the most happiness. The approach is clear while the implementation is a bit complicated and might be tedious.


(End. Original articles, please associate the author information and original URL with any reprints)

(Please specify the source  烟客旅人 sigmainfy — for any reprints,  

and please do not use it for commercial purpose)

Written on October 3, 2014