#include <stdio.h> #include <string.h> #include <stdlib.h> #include <conio.h> #define N 110 #define M N*(N-1)/2
typedef struct { int from; int to; int weight; }edge;
edge e[M]; int parent[M]; int rank[M];
int find(int x) { int y, z;
y = x; while(parent[y] != y) y = parent[y]; while(x != y) { z = parent[x]; parent[x] = y; x = z; } return y; }
void _union(int x, int y) { if(rank[x] > rank [y]) { parent[y] = x; } else { if(rank[x] == rank[y]) rank[y]++; parent[x] = y; } }
int cmp(const void *p, const void *q) { return ((edge *)p)->weight > ((edge *)q)->weight ? 1 : -1; }
int main() { int i, j, x, a, k, y; int n, sum; freopen("in.txt", "r", stdin); while(scanf("%d", &n) != EOF) { k = 0; memset(e, 0, sizeof(e)); memset(rank, 0, sizeof(rank)); memset(parent, 0, sizeof(parent)); for(i=0; i<n; i++) for(j=0; j<n; j++) { if(j <= i) scanf("%d", &a); else { scanf("%d", &e[k].weight); e[k].from = i+1; e[k].to = j+1; parent[k] = k; k++; } } qsort(e, k, sizeof(e[0]), cmp); sum = 0; for(i=0; i<k; i++) { x = find(e[i].from); y = find(e[i].to); if(x != y) { printf("%d %d\n", e[i].from, e[i].to); sum += e[i].weight; _union(x, y); } } printf("%d\n", sum); } getch(); return 0; }
|