题目:http://poj.org/problem?id=1258
完全模板题。。。和大水题poj 2485 一样。。。
目的:增强自信心。。。
代码:
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 500;
struct Edge{
int x, y, w;
};
Edge e[maxn*maxn];
int f[maxn];
int v[maxn][maxn];
int find(int x) {
if (x != f[x])
return f[x] = find(f[x]);
return x;
}
bool cmp(Edge a, Edge b) {
return a.w < b.w;
}
int main() {
int t, n;
int i, j, cnt, tmp, shortest, sel;
// freopen("in", "r", stdin);
while (scanf("%d", &n) != EOF) {
cnt = 0;
for (i = 0; i < n; i++) {
f[i] = i;
for (j = 0; j < n; j++)
if (scanf("%d", &tmp) && i > j) {
e[cnt].x = i;
e[cnt].y = j;
e[cnt].w = tmp;
cnt++;
}//if
}//for
shortest = sel = 0;
sort(e, e + cnt, cmp);
for (i = 0; i < cnt; i++) {
int a, b;
a = find(e[i].x);
b = find(e[i].y);
if (a != b) {
f[a] = b;
shortest += e[i].w;
if (++sel == n - 1) break;
}//if
}//for
printf("%d\n", shortest);
}//while
return 0;
}