题目描述:
Assume the coasting is an infinite straight line. Land is in one side of coasting, sea in the other. Each small island is a point locating in the sea side. And any radar installation, locating on the coasting, can only cover d distance, so an island in the sea can be covered by a radius installation, if the distance between them is at most d.
We use Cartesian coordinate system, defining the coasting is the x-axis. The sea side is above x-axis, and the land side below. Given the position of each island in the sea, and given the distance of the coverage of the radar installation, your task is to write a program to find the minimal number of radar installations to cover all the islands. Note that the position of an island is represented by its x-y coordinates.
Input
The input consists of several test cases. The first line of each case contains two integers n (1 n 1000) and d, where n is the number of islands in the sea and d is the distance of coverage of the radar installation. This is followed by n lines each containing two integers representing the coordinate of the position of each island. Then a blank line follows to separate the cases.
The input is terminated by a line containing pair of zeros.
Output
For each test case output one line consisting of the test case number followed by the minimal number of radar installations needed. "-1" installation means no solution for that case.
Sample Input
3 2
1 2
-3 1
2 1
1 2
0 2
0 0
Sample Output
Case 1: 2
Case 2: 1
题目大意:
在坐标系内给你一堆点的坐标,你要找到一系列的圆,这些圆的半径是固定的并且圆心必须在x轴上,还要满足这些圆要覆盖所有给出的点,问你这样的圆最少需要几个。
分析:
本题的关键点在于转化。
首先我们要想到要使圆的个数最少,圆心的位置是关键。所以问题变成了找圆心。于是我们就可以把所有给出点做一个转化处理,利用半径把它转化为在x轴上的一个区间(即利用勾股定理),使得所有能覆盖住这个点的圆心一定在这个区间内。这样,把这一堆点转化成了一系列的区间,我们的任务就变成了在这些区间中取最少的点使得每个区间内至少有一个点。接下来就是常见的贪心法解区间问题了。
此处的区间问题有点不同,我们要尽量选择那些区间重叠部分的点,而且一个区间内尽量保持只有一个点。我采用的方式是按区间的起始位置进行排序,接着遍历一遍这些区间,发现区间有重叠,就把这个区间缩小为重叠部分。这样的话,最后得到的结果实际上就变成了一系列不会重叠的区间,记录一下有几个区间自然就需要几个点。
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
struct node
{
int b,e;
} sp[1005];
bool cmp(node q,node w)
{
if(q.b!=w.b)
return q.b<w.b;
else
return q.e<w.e;
}
int main()
{
int n,d;
int T=0;
while(cin >> n >> d&&n&&d)
{
T++;
memset(sp,0,sizeof(sp));
int x,y;
int f=0;
for(int i =0 ; i < n; i++)
{
cin >> x >> y;
if(y>d) //特判一下会不会有不能达到的点
{
f=1;
break;
}
//转化,具体的自己做一个图就会明白了
int s = sqrt(d*d-y*y);
sp[i].b=x-s;
sp[i].e=x+s;
}
int ans=1;
if(f)
ans=-1;
else
{
sort(sp,sp+n,cmp);
for(int i=1; i < n; i++)
{
if(sp[i].b<=sp[i-1].e)
sp[i].e=min(sp[i-1].e,sp[i].e);
else
ans++;
}
}
cout << "Case "<< T<<": "<<ans << endl;
}
}
反思:
本题的转化部分很快就想到了,但在区间问题的处理上费了很大的劲。思维明显是不够好的。