Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 28106 | Accepted: 13266 |
Description
The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.
Input
Output
Sample Input
9 A 2 B 12 I 25 B 3 C 10 H 40 I 8 C 2 D 18 G 55 D 1 E 44 E 2 F 60 G 38 F 0 G 1 H 35 H 1 I 35 3 A 2 B 10 C 40 B 1 C 20 0
Sample Output
216
30
最小生成樹模板題
kruskal
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <string>
#include <iostream>
#include <algorithm>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <bitset>
#include <vector>
#include <functional>
using namespace std;
#define ll long long
#define mem(a, b) memset(a, b, sizeof(a))
#define debug() puts("FFFFFFFF!!!!");
const int maxn = 100;
const int inf = 0x3f3f3f3f;
int n;
int cnt;
int par[maxn];
struct edge {
int u;
int v;
int cost;
}t[maxn];
bool cmp(edge a, edge b) {
return a.cost < b.cost;
}
int find(int x) {
if (x == par[x]) return x;
return par[x] = find(par[x]);
}
int kruskal() {
sort(t, t + cnt, cmp);
int ans = 0;
for (int i = 0; i <= n; i ++) {
par[i] = i;
}
for (int i = 0; i < cnt; i ++) {
edge e = t[i];
if (find(e.u) != find(e.v)) {
int x = find(e.u);
int y = find(e.v);
par[x] = y;
ans += e.cost;
}
}
return ans;
}
int main()
{
int m, w;
string s1, s2;
while (cin >> n && n) {
cnt = 0;
for (int i = 1; i < n; i ++) {
cin >> s1 >> m;
for (int j = 0; j < m; j ++) {
cin >> s2 >> w;
int v = s2[0] - 'A' + 1;
t[cnt].u = i;
t[cnt].v = v;
t[cnt].cost = w;
cnt ++;
}
}
int ans = kruskal();
cout << ans << endl;
}
}
最小生成樹入門:http://www.cnblogs.com/biyeymyhjob/archive/2012/07/30/2615542.html