标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 51528 | Accepted: 21486 |
Description
Input
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
Source
题目大意:FarmerJohn的农村划分为n个区域,需要架设光纤网络连通。每两个区域间架设光纤所需费用不同,给出两两之间的架设价格,求连通所有地块的最小费用。
翻文件夹时偶然发现了这题,标注是最小生成树基本练习,受zhx大神的影响,我是不会去写prim的,于是我就用kruskal水掉了这题,不过一开始被多组数据坑了……
1 #include <cstdio> 2 #include <cmath> 3 #include <cstring> 4 #include <cstdlib> 5 #include <queue> 6 #include <stack> 7 #include <vector> 8 #include <iostream> 9 #include "algorithm" 10 using namespace std; 11 typedef long long LL; 12 const int MAX=105; 13 int n,m; 14 int f[MAX][MAX]; 15 int ans; 16 struct Edge{ 17 int u,v; 18 int w; 19 }edge[MAX*MAX]; 20 int fa[MAX*MAX]; 21 int getfather(int x){ 22 if (fa[x]==x) 23 return x; 24 return fa[x]=getfather(fa[x]); 25 } 26 bool cmp(Edge x,Edge y){ 27 return x.w<y.w; 28 } 29 void init(){ 30 int i,j; 31 for (i=1;i<=n;i++) 32 for (j=1;j<=n;j++) 33 scanf("%d",&f[i][j]); 34 m=0; 35 for (i=1;i<=n;i++) 36 for (j=i+1;j<=n;j++) 37 {m++; 38 edge[m].u=i; 39 edge[m].v=j; 40 edge[m].w=f[i][j]; 41 } 42 for (i=1;i<=m;i++) 43 fa[i]=i; 44 sort(edge+1,edge+m+1,cmp); 45 } 46 int main(){ 47 freopen ("net.in","r",stdin); 48 freopen ("net.out","w",stdout); 49 while (scanf("%d\n",&n)!=EOF){ 50 init();int i,j; 51 ans=0; 52 int tx,ty; 53 for (i=1;i<=m;i++) 54 {tx=getfather(edge[i].u); 55 ty=getfather(edge[i].v); 56 if (tx!=ty) 57 {fa[tx]=ty; 58 ans+=edge[i].w; 59 } 60 } 61 printf("%d\n",ans);} 62 return 0; 63 }
标签:
原文地址:http://www.cnblogs.com/Michaelzzn/p/5725207.html