Watering Grass(贪心 区间覆盖)
n sprinklers are installed in a horizontal strip of grass l meters long and w meters wide. Each sprinkler is installed at the horizontal center line of the strip. For each sprinkler we are given its position as the distance from the left end of the center line and its radius of operation.
What is the minimum number of sprinklers to turn on in order to water the entire strip of grass?
Input
Input consists of a number of cases. The first line for each case contains integer numbers n, l and w with n <= 10000. The next n lines contain two integers giving the position of a sprinkler and its radius of operation. (The picture above illustrates the first case from the sample input.)
Output
For each test case output the minimum number of sprinklers needed to water the entire strip of grass. If it is impossible to water the entire strip output -1.
题意: 给出多个圆心和半径,问最少需要多少个圆,才能把花带覆盖完全,如果不能完全覆盖,输出-1
思路: 将草地的上边界作为要覆盖的区间,计算出每个洒水器覆盖的区间范围,不能覆盖的舍去,然后将洒水器按覆盖范围的左边界升序排列,查找,第一个是必用的,然后找左边界尽可能大且小于上一个右边界的,右边界尽可能的大,更新重复即可
AC代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct pp
{
double a,b;
}p[11000];
bool cmp(pp x,pp y)
{
if(x.a!=y.a)
return x.a<y.a;
return x.b>y.b;
}
int main()
{
int n,i,j;
double l,w,aa,bb;
while(~scanf("%d%lf%lf",&n,&l,&w))
{
int k=0;
double maxx=-1;
for(i=0;i<n;i++)
{
scanf("%lf%lf",&aa,&bb);
if(bb*2<=w)
continue;
else
{
p[k].a=aa-sqrt(bb*bb-w*w/4.0);
p[k].b=aa+sqrt(bb*bb-w*w/4.0);//计算覆盖区间
if(p[k].b>maxx)//找最大右边界
maxx=p[k].b;
k++;
}
}//printf("%lf--\n",maxx);
sort(p,p+k,cmp);
// for(i=0;i<k;i++)
// printf("%lf %lf++\n",p[i].a,p[i].b);
int f=0;
if(p[0].a>0||maxx<l)//边界
{
printf("-1\n");
continue;
}
double x=0;
int sum=0;
while(x<l)
{
double y=x;
for(i=0;i<k;i++)
{
if(p[i].b>x&&p[i].a<=y)//注意x,y
x=p[i].b;
}
if(y==x&&y<l)
{
f=1;
break;
}
sum++;
}
if(!f)
printf("%d\n",sum);
else
printf("-1\n");
}
return 0;
}