注意:多组数据输入。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define MAXN 110 using namespace std; int fa[MAXN]; int n,tot,sum,ans; struct nond{ int x,y,z; }v[MAXN*MAXN]; int cmp(nond a,nond b){ return a.z<b.z; } int find(int x){ if(fa[x]==x) return x; else return fa[x]=find(fa[x]); } int main(){ while(scanf("%d",&n)!=EOF){ tot=0;ans=0;sum=0; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ int x;scanf("%d",&x); if(i==j) continue; v[++tot].x=i;v[tot].y=j;v[tot].z=x; } sort(v+1,v+1+tot,cmp); for(int i=1;i<=n;i++) fa[i]=i; for(int i=1;i<=tot;i++){ int dx=find(v[i].x); int dy=find(v[i].y); if(dx==dy) continue; fa[dy]=dx;sum++; ans+=v[i].z; if(sum==n-1) break; } cout<<ans<<endl; } }