POJ-1258 Agri-Net 最小生成树
最直接的最小生成树,不解释了。
代码如下:
#include <cstring> #include <cstdlib> #include <cstdio> #include <algorithm> using namespace std; int N, pos, set[105]; struct Node { int x, y, dist; bool operator < (Node t) const { return dist < t.dist; } }e[10005]; int find(int x) { return set[x] = x == set[x] ? x : find(set[x]); } void merge(int a, int b) { set[a] = b; } int main() { int c, cnt, ans; while(scanf("%d", &N) == 1) { pos = cnt = ans = 0; for (int i = 1; i <= N; ++i) { set[i] = i; for (int j = 1; j <= N; ++j) { scanf("%d", &c); ++pos; e[pos].x = i, e[pos].y = j, e[pos].dist = c; } } sort(e+1, e+1+pos); for (int i = 1; i <= pos; ++i) { int a = find(e[i].x), b = find(e[i].y); if (a != b) { merge(a, b); ans += e[i].dist; ++cnt; if (cnt == N-1) { break; } } } printf("%d\n", ans); } return 0; }