水题,直接贴代码了
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define LLEN 105
int map[LLEN][LLEN];
int p[LLEN];
typedef struct Edge {
int u, v;
int w;
}Edge;
Edge edge[10050];
int cmp(const void *a, const void *b) {
Edge aa = *(const Edge *)a;
Edge bb = *(const Edge *)b;
return aa.w - bb.w;
}
int find(int x) {
int s;
for(s = x; p[s] >= 0; s = p[s]);
while(s != x) {
int tmp = p[x];
p[x] = s;
x = tmp;
}
return s;
}
void init(int x) {
for(int i = 1; i <= x; i++) {
p[i] = -1;
}
}
void uion(int a, int b) {
int t1 = find(a);
int t2 = find(b);
int tmp = p[t1] + p[t2];
if(p[t1] > p[t2]) {
p[t1] = t2;
p[t2] = tmp;
}
else {
p[t2] = t1;
p[t1] = tmp;
}
}
int kruskal(int n) {
int ans = 0;
for(int i = 0; i < n; i++) {
int u = edge[i].u;
int v = edge[i].v;
if(find(u) != find(v)) {
uion(u, v);
ans += edge[i].w;
}
}
return ans;
}
int main() {
int n, q;
while(scanf("%d", &n) != EOF) {
init(n);
memset(edge, 0, sizeof(edge));
for(int i = 1; i <= n; i++) {
for(int j = 1 ; j <= n; j++) {
scanf("%d", &map[i][j]);
}
}
scanf("%d", &q);
for(int i = 0; i < q; i++) {
int a, b;
scanf("%d%d", &a, &b);
if(find(a) != find(b)) {
uion(a, b);
}
}
int k = 0;
for(int i = 1; i <= n; i++) {
for(int j = i+1; j <= n; j++) {
edge[k].u = i;
edge[k].v = j;
edge[k++].w = map[i][j];
}
}
qsort(edge, k, sizeof(edge[0]), cmp);
printf("%d\n", kruskal(k));
}
return 0;
}