链接:http://acm.hdu.edu.cn/showproblem.php?pid=1102
源代码:
//之前的总是stack_overflow,无语啊
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;
#define INF 9999999
int village[101];
int edge[101][101];
int dis[5000][3];
int comp(const void *a,const void *b)
{
return ((int *)a)[0]-((int *)b)[0];
}
int find_set(int n)
{
if(village[n]==n)return n;
else return village[n]=find_set(village[n]);
}
int Merge(int s1,int s2)
{
int r1=find_set(s1);
int r2=find_set(s2);
if(r1==r2)return 0;
if(r1<r2)village[r2]=r1;
else village[r1]=r2;
return 1;
}
int main()
{
int n,i,j;
while(~scanf("%d",&n))
{
int sum=0,count=0,temp=0,temp1,q;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
edge[i][j]=INF;
for(int i1=1;i1<=n;i1++)
{
village[i1]=i1;
for(int j1=1;j1<=n;j1++)
{
scanf("%d",&temp1);
edge[i1][j1]=edge[j1][i1]=temp1;
}
}
int i2,j2;
scanf("%d",&q);
for(int k=1;k<=q;k++)
{
scanf("%d%d",&i2,&j2);
edge[i2][j2]=edge[j2][i2]=0;
}
for(int i3=1;i3<n;i3++)
for(int j3=i3+1;j3<=n;j3++)
{
dis[++temp][1]=i3;
dis[temp][2]=j3;
dis[temp][0]=edge[i3][j3];
}
qsort(dis+1,temp,3*sizeof(int),comp);
for(int x=1;x<=temp;x++)
{
if(find_set(dis[x][1])==find_set(dis[x][2]))continue;
Merge(dis[x][1],dis[x][2]);
sum+=dis[x][0];
count++;
if(count==n-1)break;
}
printf("%d\n",sum);
}
return 0;
}