1487:【例 2】北极通讯网络 - 题解
作者:互联网
1487:【例 2】北极通讯网络 - 题解
原题地址:点击这里
只需要找到最小生成树中第 k 大的边即可。
1 #include<cstdio> 2 #include<cmath> 3 #include<algorithm> 4 5 #define N 505 6 #define M N*N*2 7 #define K 105 8 9 using namespace std; 10 11 int n,m,k; 12 double ans=0; 13 14 struct Valiant{ 15 int x,y; 16 }P[N]; 17 double dist(int a,int b) 18 { 19 int x1=P[a].x,y1=P[a].y; 20 int x2=P[b].x,y2=P[b].y; 21 return (double)sqrt((double)(x1-x2)*(x1-x2)+(double)(y1-y2)*(y1-y2)); 22 } 23 24 struct Allan{ 25 int from,to; 26 double val; 27 }edge[M]; 28 int edge_cnt=0; 29 int head[N]; 30 void Add_edge(int from,int to,double value) 31 { 32 edge_cnt++; 33 edge[edge_cnt].from=from; 34 edge[edge_cnt].to=to; 35 edge[edge_cnt].val=value; 36 return; 37 } 38 39 int Father[N]; 40 void Union_init() 41 { 42 for(int i=1;i<=n;i++) 43 Father[i]=i; 44 return; 45 } 46 int Union_get(int x) 47 { 48 if(Father[x]==x) return x; 49 return Father[x]=Union_get(Father[x]); 50 } 51 52 int Kruskal_cnt=0; 53 bool cmp(Allan x,Allan y) 54 { 55 return x.val<y.val; 56 } 57 void Kruskal() 58 { 59 sort(edge+1,edge+m+1,cmp); 60 Union_init(); 61 for(int i=1;i<=m;i++) 62 { 63 int x=Union_get(edge[i].from); 64 int y=Union_get(edge[i].to); 65 if(x==y) continue; 66 Kruskal_cnt++; 67 Father[x]=y; 68 if(Kruskal_cnt>=n-k) 69 { 70 printf("%.2lf\n",edge[i].val); 71 return; 72 } 73 } 74 return; 75 } 76 77 int main() 78 { 79 scanf("%d%d",&n,&k); 80 if(n==k) 81 { 82 printf("0\n"); 83 return 0; 84 } 85 for(int i=1;i<=n;i++) 86 scanf("%d%d",&P[i].x,&P[i].y); 87 for(int i=1;i<=n;i++) 88 for(int j=1;j<=n;j++) 89 { 90 if(i==j) continue; 91 Add_edge(i,j,dist(i,j)); 92 Add_edge(j,i,dist(i,j)); 93 } 94 m=edge_cnt; 95 Kruskal(); 96 return 0; 97 }
标签:cnt,return,北极,int,题解,edge,1487,double,y1 来源: https://www.cnblogs.com/jerrycyx/p/16439793.html