思路:并查集板子
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #define MAXN 110 using namespace std; int fa[MAXN]; int n,m,tot,sum,ans; struct nond{ int x,y,z; }v[20001]; 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(){ scanf("%d",&n); 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; } scanf("%d",&m); for(int i=1;i<=m;i++){ int x,y; scanf("%d%d",&x,&y); v[++tot].x=x;v[tot].y=y;v[tot].z=0; } for(int i=1;i<=n;i++) fa[i]=i; sort(v+1,v+1+tot,cmp); 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; }