kruskal --- C++
#include <cstdio> #include <algorithm> using namespace std; struct aaa{ int l,r,w; bool operator < (const aaa& b) const { return w<b.w; } }a[10001]; int fa[101]; int find(int a) { if (a != fa[a]) return find(fa[a]); return a; } int main() { int n,num = 0; scanf("%d",&n); for (int i = 0; i<n; i++) for (int j = 0; j<n; j++) { scanf("%d",&a[num].w); a[num].l = i; a[num].r = j; if (i > j || i==j) a[num].w = 1000000; num++; } sort(a,a+num); for (int i = 0; i<n; i++) fa[i] = i; int nn = 0,k = 0,ans = 0; while(nn<n-1) { int faa = find(a[k].l),fab = find(a[k].r); if (faa != fab) { fa[a[k].l] = fab; fa[faa] = fab; nn++; ans += a[k].w; } k++; } printf("%d",ans); }
题目来源:code[VS]