最小生成树,用Kruskal。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct edge
{
int u;
int v;
int w;
};
edge e[10000];
int le,n,uset[110];
int root(int x)
{
if (uset[x] == x)
return x;
else
{
uset[x]=root(uset[x]);
return uset[x];
}
}
bool cmp(edge a,edge b)
{
return a.w < b.w;
}
int main()
{
int q,t1,t2,tx,ty,i,j,ans;
scanf("%d",&n);
le=0;
for (i=1; i<=n; i++)
{
uset[i]=i;
for (j=1; j<=n; j++)
{
scanf("%d",&t1);
if (i<j)
{
e[le].u=i;
e[le].v=j;
e[le].w=t1;
le++;
}
}
}
scanf("%d",&q);
while (q--)
{
scanf("%d%d",&t1,&t2);
tx=root(t1);
ty=root(t2);
uset[tx]=ty;
}
sort(e,e+le,cmp);
ans=0;
for (i=0; i<le; i++)
{
tx=root(e[i].u);
ty=root(e[i].v);
if (tx != ty)
{
uset[tx]=ty;
ans+=e[i].w;
}
}
printf("%d\n",ans);
}