P4047 部落划分 :
问题描述
题目简述
聪聪研究发现,荒岛野人总是过着群居的生活,但是,并不是整个荒岛上的所有野人都属于同一个部落,野人们总是拉帮结派形成属于自己的部落,不同的部落之间则经常发生争斗。只是,这一切都成为谜团了——聪聪根本就不知道部落究竟是如何分布的。
不过好消息是,聪聪得到了一份荒岛的地图。地图上标注了 n 个野人居住的地点(可以看作是平面上的坐标)。我们知道,同一个部落的野人总是生活在附近。我们把两个部落的距离,定义为部落中距离最近的那两个居住点的距离。聪聪还获得了一个有意义的信息——这些野人总共被分为了 k个部落!这真是个好消息。聪聪希望从这些信息里挖掘出所有部落的详细信息。他正在尝试这样一种算法:
对于任意一种部落划分的方法,都能够求出两个部落之间的距离,聪聪希望求出一种部落划分的方法,使靠得最近的两个部落尽可能远离。
输入/输出格式
输入格式:
输入文件第一行包含两个整数 n 和 k,分别代表了野人居住点的数量和部落的数量。
接下来 n 行,每行包含两个整数 x,y,描述了一个居住点的坐标。
输出格式:
输出一行一个实数,为最优划分时,最近的两个部落的距离,精确到小数点后两位。
样例
输入样例:
4 2
0 0
0 1
1 1
1 0
输出样例:
1.00
问题分析
解题思路
这题其实和r32中的几乎一模一样,只不过是换了一个说法。实际上就是将最小生成树的最大的k条边作为部落之间划分的边,其他的权值较小的边均为划分中的边,最后输出最大的k条边中最小的一条即可。
参考代码
#include <iostream>
#include <queue>
#include <cstring>
#include <vector>
#include <cmath>
using namespace std;
class edge
{
public:
int from;
int to;
float weight;
edge(int u,int v,float w)
{
from=u;
to=v;
weight=w;
}
bool operator <(const edge& e) const
{
return weight>e.weight;
}
};
class point
{
public:
int p_x;
int p_y;
point(int xx,int yy)
{
p_x=xx;
p_y=yy;
}
};
priority_queue<edge> pq;
vector<edge> edges;
vector<point> points;
int p[1010];
int n,k;
void init()
{
while(!pq.empty()) pq.pop();
edges.clear();
points.clear();
for(int i=0;i<1010;i++)
{
p[i]=i;
}
}
void addedge(int index)
{
point p1=points[index];
for(int i=0;i<index;i++)
{
point p2=points[i];
float dist=sqrt((p1.p_x-p2.p_x)*(p1.p_x-p2.p_x)+(p1.p_y-p2.p_y)*(p1.p_y-p2.p_y));
edge te(i,index,dist);
//printf("add edge (%d %d %f)\n",te.from,te.to,te.weight);
pq.push(te);
}
}
int find(int u)
{
if(p[u]!=u) p[u]=find(p[u]);
return p[u];
}
void kruskal()
{
int cnt=0;
while(cnt!=n-1)
{
edge te=pq.top();
pq.pop();
//printf("get edge (%d %d %f)\n",te.from,te.to,te.weight);
int a=find(te.from);
int b=find(te.to);
//printf("a=%d b=%d\n",&a,&b);
if(a!=b)
{
edges.push_back(te);
p[a]=b;
cnt++;
}
}
}
int main()
{
init();
scanf("%d %d",&n,&k);
for(int i=1;i<=n;i++)
{
int x,y;
scanf("%d %d",&x,&y);
point tp(x,y);
points.push_back(tp);
addedge(points.size()-1);
}
kruskal();
printf("%.2f",edges[edges.size()-k+1].weight);
return 0;
}
心得体会
重复度非常高,代码几乎是一模一样的,这里不再赘述了。