Kruskal
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define N 100002
struct node {
int u, v, w;
node() {}
node(int _u, int _v, int _w):u(_u), v(_v), w(_w) {}
};
vector<node> edge;
int n, m, f[N];
bool cmp(const node &x, const node &y) {
return x.w < y.w;
}
int find_set(int x) {
if (f[x] == x) return x;
return f[x] = find_set(f[x]);
}
int Kruskal() {
sort(edge.begin(), edge.end(), cmp);
for (int i=1; i<=n; i++) f[i] = i;
int ans = 0;
for (int i=0, u, v, w; i<edge.size(); i++) {
u = edge[i].u, v = edge[i].v, w = edge[i].w;
u = find_set(u), v = find_set(v);
if (u == v) continue;
f[u] = v;
ans += w;
}
return ans;
}
int main() {
while (scanf("%d", &n)!=EOF) {
edge.clear();
int a[105][105];
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)scanf("%d",&a[i][j]);
for(int i=1;i<=n;i++)//郁闷,下标要从1开始
for (int j=1; j<i; j++) {
//scanf("%d%d%d", &a, &b, &c);
edge.push_back(node(i, j, a[i][j]));
//edge.push_back(node(j, i, a[i][j]));
}
printf("%d\n", Kruskal());
}
return 0;
}
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define N 1003
#define inf 0x3f3f3f3f
struct node {
int v, w;
node () {}
node(int _v, int _w) : v(_v), w(_w) {}
};
vector<node> g[N];
int n, m, d[N];
bool vis[N];
int prim() {
memset(vis, false, sizeof(vis));
memset(d, 0x3f, sizeof(d));
int ans = d[1] = 0;
for (int i=0; i<n; i++) {
int k = 0, mi = inf;
for (int j=1; j<=n; j++) if (!vis[j] && d[j] < mi)
mi = d[j], k = j;
if (k == 0) break;
vis[k] = true;
ans += mi;
for (int j=0, u; j<g[k].size(); j++)
if (!vis[u = g[k][j].v] && d[u] > g[k][j].w)
d[u] = g[k][j].w;
}
return ans;
}
int main() {
while (scanf("%d", &n)!=EOF) {
for (int i=0; i<=n; i++) g[i].clear();
int a[105][105];
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)scanf("%d",&a[i][j]);
for (int i=1; i<=n; i++)
for(int j=1;j<i;j++){
g[i].push_back(node(j, a[i][j]));
g[j].push_back(node(i, a[i][j]));
}
printf("%d\n", prim());
}
return 0;
}