We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
#include
#define M 120
#define INF 0x3f3f3f3f
using namespace std;
int bin[M],m[M][M];
struct node
{
int i,j,w;//i,j表示的是从i到j,需要w的距离
};
node fr[M*M];
bool comp(node &a,node &b)
{
return a.w
}
int findx(int x)//找根
{
int r=x;
while(bin[r]!=r)
r=bin[r];
return r;
}
int kruskal(int n,int m)
{
sort(fr,fr+m,comp);//将需要的距离从小到大排列
int ans=0;
for(int i=0;i
{
int fx=findx(fr[i].i);
int fy=findx(fr[i].j);
//cout<<fx<<" "<<fy<<endl;
if(fx!=fy)
{
ans+=fr[i].w;
bin[fx]=fy;
//cout<<"YES"<<endl;
}
}
return ans;
}
int main()
{
//freopen("in.txt","r",stdin);
int n,t;
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
bin[i]=i;
int m=0,k;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
scanf("%d",&k);
//cout<<k<<endl;
if(i>=j) continue;
fr[m].i=i;
fr[m].j=j;
fr[m++].w=k;
}
scanf("%d",&t);
int a,b;
for(int i=1;i<=t;i++)
{
scanf("%d%d",&a,&b);
int fx=findx(a);
int fy=findx(b);
bin[fx]=fy;
}
//for(int i=1;i<=n;i++)
// cout<<bin[i]<<" ";
//cout<<endl;
//cout<<m<<endl;
int ans=kruskal(n,m);
printf("%d\n",ans);
}
return 0;
}