1 #include<stdio.h>
2 int a[10005],p[10005],q[10005],father[10005];
3 int find(int x)
4 {
5 if (father[x]!=x) father[x]=find(father[x]);
6 return(father[x]);
7 }
8 void qsort(int l,int r)
9 {
10 int i,j,x,y;
11 i=l; j=r;
12 x=a[(i+j)/2];
13 while (i<=j)
14 {
15 while (a[i]<x) i++;
16 while (x<a[j]) j--;
17 if (i<=j) {y=p[i];p[i]=p[j];p[j]=y;
18 y=q[i];q[i]=q[j];q[j]=y;
19 y=a[i];a[i]=a[j];a[j]=y;
20 i++; j--;}
21 }
22 if (l<j) qsort(l,j);
23 if (i<r) qsort(i,r);
24 return;
25 }
26 int main()
27 {
28 int i,j,n,m,x,s1,s2,sum,length[205][205];
29 while (~scanf("%d",&n))
30 {
31 for (i=1;i<=n;i++)
32 for (j=1;j<=n;j++) scanf("%d",&length[i][j]);
33 x=0;
34 for (i=2;i<=n;i++)
35 for (j=1;j<i;j++) {x++; a[x]=length[i][j];p[x]=i; q[x]=j; }
36 qsort(1,x);
37 for (i=1;i<=n;i++) father[i]=i;
38 scanf("%d",&m);
39 for (i=1;i<=m;i++) {scanf("%d%d",&s1,&s2); father[find(s1)]=find(s2); }
40 sum=0;
41 for (i=1;i<=x;i++)
42 {
43 if (find(p[i])!=find(q[i]))
44 {
45 father[find(p[i])]=find(q[i]);
46 sum+=a[i];
47 }
48 }
49 printf("%d\n",sum);
50 }
51 return(0);
52 }
http://acm.hdu.edu.cn/showproblem.php?pid=1102