UVa 11710 - Expensive subway

题目:上班坐高铁,需要购买月票,选择能够到达所有城市的最小花费的月票。

分析:图论,最小生成树。利用prim算法求解即可。

说明:(⊙v⊙)。

#include 
#include 
#include 

using namespace std;

const int INF = 100000000; 

int path[404][404];
int used[404], dist[404];

int main()
{
	int    n, m, u, v, d;
	string city1, city2, start;
	while (cin >> n >> m && n) {
		map M;
		for (int i = 1; i <= n; ++ i) {
			cin >> city1;
			M[city1] = i;
		}
		for (int i = 1; i <= n; ++ i) {
			for (int j = i; j <= n; ++ j) {
				path[i][j] = INF;
				path[j][i] = INF;  
			}
		}
		for (int i = 1; i <= m; ++ i) {
			cin >> city1 >> city2 >> d;
			u = M[city1];
			v = M[city2];
			path[u][v] = d;
			path[v][u] = d;
		}
		cin >> start;
		int now = M[start], ans = 0;
		
		for (int i = 1; i <= n; ++ i) {
			dist[i] = INF;
			used[i] = 0;
		}
		dist[now] = 0;
		used[now] = 1;
		for (int i = 2; i <= n; ++ i) {
			for (int j = 1; j <= n; ++ j) {
				if (!used[j] && dist[j] > path[now][j]) {
					dist[j] = path[now][j];
				}
			}
			int min = INF;
			for (int j = 1; j <= n; ++ j) {
				if (!used[j] && dist[j] < min) {
					min = dist[j];
					now = j;
				}
			}
			if (dist[now] != INF) {
				ans += dist[now];
				used[now] = 1;
			}
		}
		
		int count = 0;
		for (int i = 1; i <= n; ++ i) {
			count += used[i];
		}
		if (count == n) {
			cout << ans << endl;
		}else {
			cout << "Impossible" << endl;
		}
	} 
    return 0;
}


你可能感兴趣的:(解题报告,图论)