Highway
Bob is a skilled engineer. He must design a highway that crosses a region with few villages. Since this
region is quite unpopulated, he wants to minimize the number of exits from the highway. He models
the highway as a line segment S (starting from zero), the villages as points on a plane, and the exits
as points on S. Considering that the highway and the villages position are known, Bob must find the
minimum number of exists such that each village location is at most at the distance D from at least
one exit. He knows that all village locations are at most at the distance D from S.
Input
The program input is from the standard input. Each data set in the file stands for a particular set of
a highway and the positions of the villages. The data set starts with the length L (fits an integer) of
the highway. Follows the distance D (fits an integer), the number N of villages, and for each village
the location (x, y). The program prints the minimum number of exits. White spaces can occur freely
in the input. The input data are correct and terminate with an end of file.
Output
For each set of data the program prints the result to the standard output from the beginning of a line.
Note: An input/output sample is in the table below. There is a single data set. The highway length
L is 100, the distance D is 50. There are 3 villages having the locations (2, 4), (50, 10), (70, 30). The
result for the data set is the minimum number of exits: 1.
Sample Input
100
50
3
2 4
50 10
70 30
Sample Output
1
题意大约是给你无限多个点,还有一个D的值,要我们求在x轴上有尽量少的点的个数,使得对于给定的每个点,都有一个选出的点离他的距离不超过D。
这题目刚开始看着挺唬人的,但是仔细思考了一下,画了一个图:每个点为圆心,D为半径画一个圆。与x相加的部分就是我们要求的点的集合了(也就是个区间),然后我们就发现了这道题目就转换成了贪心的经典问题区间选点问题。
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
int n;
double r,L;
struct node //建立node来储存点和区间。
{
double x,y;
}v[100010],p[100010]; //v来存点,p来存区间。
bool cmp(const node &a,const node &b) //比较函数,以区间左端的排序。
{
return a.x<b.x;
}
double ld(node z) //求欧几里德距离的函数。
{
return sqrt((r*r)-(z.y*z.y));
}
int main()
{
while(cin>>L>>r>>n)
{
int sum=1;
for(int i=0;i<n;i++)
{
cin>>v[i].x>>v[i].y;
double ll=ld(v[i]);
p[i].x=v[i].x-ll;
p[i].y=v[i].x+ll;
}
sort(p,p+n,cmp); //因为这里的贪心策略是第一个区间要先取点。
double ly=p[0].y;
for(int i=1;i<n;i++)
{
if(p[i].x<=ly) ly=min(ly,p[i].y);
else
{
ly=p[i].y;
sum++;
}
if(ly>L) ly=L; //题目的区间是有L限制的。
}
cout<<sum<<endl;
}
}