聪聪研究发现,荒岛野人总是过着群居的生活,但是,并不是整个荒岛上的所有野人都属于同一个部落,野人们总是拉帮结派形成属于自己的部落,不同的部落之间则经常发生争斗。只是,这一切都成为谜团了——聪聪根本就不知道部落究竟是如何分布的。 不过好消息是,聪聪得到了一份荒岛的地图。地图上标注了N个野人居住的地点(可以看作是平面上的坐标)。我们知道,同一个部落的野人总是生活在附近。我们把两个部落的距离,定义为部落中距离最近的那两个居住点的距离。聪聪还获得了一个有意义的信息——这些野人总共被分为了K个部落!这真是个好消息。聪聪希望从这些信息里挖掘出所有部落的详细信息。他正在尝试这样一种算法:
对于任意一种部落划分的方法,都能够求出两个部落之间的距离,聪聪希望求出一种部落划分的方法,使靠得最近的两个部落尽可能远离。 例如,下面的左图表示了一个好的划分,而右图则不是。请你编程帮助聪聪解决这个难题。
Input
第一行包含两个整数N和K(1< = N < = 1000,1< K < = N),分别代表了野人居住点的数量和部落的数量。
接下来N行,每行包含两个正整数x,y,描述了一个居住点的坐标(0 < =x, y < =10000)
Output
输出一行,为最优划分时,最近的两个部落的距离,精确到小数点后两位。
Sample Input
4 2
0 0
0 1
1 1
1 0
0 0
0 1
1 1
1 0
Sample Output
1.00
题目大意是分为 n 个点, 分为k个部分, 求 最小的两个集合中两点的距离。
分析:最小生成树, 每次合并两个点, 直到合并了n-k条边, 即已经分成k个部分, 第n-k+1的不构成环的边的边权即为所求。
下面贴一份错误代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
struct node{
int a, b;
double c;
bool operator < (const node & A) const{
return c < A.c;
}
}d[500009];
int x[1001], y[1001], f[1001], cnt, t;
void getedge(int i, int j){
d[++cnt].a = i; d[cnt].b = j;
d[cnt].c = 1.0*sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
}
int find(int x){
return x == f[x]? x: f[x] = find(f[x]);
}
int main(){
int i, j, n, a, b, k;
scanf("%d%d", &n, &k);
for(i = 1; i <= n; i++) scanf("%d%d", &x[i], &y[i]);
for(i = 1; i <= n; i++) f[i] = i;
for(i = 1; i <= n; i++){
for(j = i+1; j <= n; j++){
getedge(i,j);
}
}
sort(d+1,d+cnt+1);
for(i = 1; i <= cnt; i++){
a = find(d[i].a); b = find(d[i].b);
if(a != b){
f[b] = a;
n--;
}
if(n == k){
printf("%.2lf", d[i+1].c);
break;
}
}
return 0;
}
上面这份代码错哪里了呢?我调了很久, 发现是第i+1条边的a和b可能在同一个环中QAQ,太蠢了。下面是AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
struct node{
int a, b;
double c;
bool operator < (const node & A) const{
return c < A.c;
}
}d[500009];
int x[1001], y[1001], f[1001], cnt, t;
void getedge(int i, int j){
d[++cnt].a = i; d[cnt].b = j;
d[cnt].c = 1.0*sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
}
int find(int x){
return x == f[x]? x: f[x] = find(f[x]);
}
int main(){
int i, j, n, a, b, k;
scanf("%d%d", &n, &k);
for(i = 1; i <= n; i++) scanf("%d%d", &x[i], &y[i]);
for(i = 1; i <= n; i++) f[i] = i;
for(i = 1; i <= n; i++){
for(j = i+1; j <= n; j++){
getedge(i,j);
}
}
sort(d+1,d+cnt+1);
for(i = 1; i <= cnt; i++){
a = find(d[i].a); b = find(d[i].b);
if(a != b){
f[b] = a;
t++;
}
if(t == n-k+1){
printf("%.2lf", d[i].c);
break;
}
}
return 0;
}