并查集+kruskal==>MST
效率很低
#include <iostream> using namespace std; #define MAX 105 //自己设置最大值 // father[x]表示x的父节点 int father[MAX]; // rank[x]表示x的秩 int rank[MAX]; typedef struct { int i,j; int distance; } E; E edges[MAX*MAX]; // 初始化 void Make_Set(int n) { for(int i=1; i<=n; ++i) { father[i] = i; rank[i] = 0; } } // 查找 int Find_Set(int x) { if(x != father[x]) return Find_Set(father[x]); return x; } // 合并 void Union(int x, int y) { x = Find_Set(x); y = Find_Set(y); if(x == y) // x,y在同一个集合 return; if(rank[x] > rank[y]) father[y] = x; else if(rank[x] < rank[y]) father[x] = y; else { rank[y]++; father[x] = y; } } bool myfunction ( const E a , const E b ) { return (a.distance<b.distance); } int main() { freopen("input.txt","r",stdin); int i,j,n,m,u,v; int count,Sum; while(cin>>n&&n!=0) { count=Sum=0; for(i=0; i<n; i++) for(j=0; j<n; j++) { edges[i*n+j].i=i; edges[i*n+j].j=j; cin>>edges[i*n+j].distance; } sort(edges,edges+(n*n),myfunction); Make_Set(n); for(i=0; i<n*n; i++) { if(count==n-1) break; if(edges[i].i!=edges[i].j&&(Find_Set(edges[i].i)!=Find_Set(edges[i].j))) { Union(edges[i].i,edges[i].j); Sum+=edges[i].distance; } } cout<<Sum<<endl; } return 0; }