I can play well in a village water costs spent Wi, water can also be connected to the water village
And because the village is not possible without a well drilling (ie, there is at least one village wells, connected to the rest of the village it)
In fact it can be understood as well regarded as the first N + 1 villages, the village needs to have connected with the N + 1 village, in order to ensure that all villages have water
I is connected to the village costs village N + 1, can be directly understood the cost of drilling as Wi
The remainder of the minimum spanning tree can be used Kruskal
1 /* 2 Written By StelaYuri 3 */ 4 #include<cstdio> 5 #include<algorithm> 6 using namespace std; 7 struct tube{ 8 int from,to,cost; 9 bool operator < (const tube &a) const{ 10 return cost<a.cost; 11 } 12 }p[90001]; 13 int gp[301]; 14 int find(int a){ 15 return a==gp[a]?a:(gp[a]=find(gp[a])); 16 } 17 int main(){ 18 int i,j,N,d,cnt=0,k=0,sum; 19 scanf("%d",&N); 20 for(i=1;i<=N;i++){ 21 scanf("%d",&d); 22 p[cnt].from=i; 23 p[cnt].to=N+1; 24 p[cnt++].cost=d; 25 gp[i]=i; 26 } 27 for(i=1;i<=N;i++) 28 for(j=1;j<=N;j++){ 29 scanf("%d",&d); 30 if(i==j) 31 continue; 32 p[cnt].from=i; 33 p[cnt].to=j; 34 p[cnt++].cost=d; 35 } 36 sort(p,p+cnt); 37 for(sum=i=0;i<cnt;i++){ 38 if(k==N) 39 break; 40 if(find(p[i].from)!=find(p[i].to)){ 41 gp[find(p[i].to)]=find(p[i].from); 42 sum+=p[i].cost; 43 k++; 44 } 45 } 46 printf("%d\n",sum); 47 48 return 0; 49 }