Problem E Watering Grass Input:standard input Output:standard output Time Limit:3 seconds
nsprinklers are installed in a horizontal strip of grasslmeters long andwmeters 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 numbersn,landwwithn<= 10000. The nextnlines 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.
Sample input
8 20 2
5 3
4 1
1 2
7 2
10 2
13 3
16 2
19 4
3 10 1
3 5
9 3
6 1
3 10 1
5 3
1 1
9 1
Sample Output
6
2
-1
转化为区间嵌套,用圆和矩形的边形成的弦区间,贪心求之,注意精度问题
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstdlib>
using namespace std;
struct data{
double x,y;
}f[10010];
#define eps 1e-7
inline int ifcmp(double x){//精度
if (x > -eps) return 1;
else return -1;
}
bool cmp(data a,data b)
{
return a.x<b.x||(a.x==b.x&&a.y>b.y);
}
int main()
{
int n,l,w,i,j,k,a,b;
while(scanf("%d%d%d",&n,&l,&w)!=EOF)
{
for(i=0,j=0;i<n;i++)
{
scanf("%d%d",&a,&b);
if(2*b<w)
continue;
double tem;
tem=sqrt((double)b*b-(double)w*w/4.0);//半弦
f[j].x=a-tem;
f[j].y=a+tem;
j++;
}
sort(f,f+j,cmp);
int pre=0,pos,sum=0,max_j;
sum=1;
i=1;
max_j=0;
while(true)
{
bool flag=false;
while(ifcmp(f[pre].y-f[i].x)>0&&i<j)
{
flag=true;
if(ifcmp(f[i].y-f[max_j].y)>0)
max_j=i;
i++;
}
if(!flag||(i>j&&ifcmp(f[max_j].y-(double)l)<0))
{
sum=-1;
break;
}
pre=max_j;
sum++;
if(ifcmp(f[max_j].y-(double)l)>0)
break;
}
printf("%d\n",sum);
}
}
浇水草地问题解析
本文介绍了一个经典的算法问题——浇水草地问题。该问题涉及通过给定的洒水器位置和操作半径来确定最少需要激活多少个洒水器才能浇灌整片草地。文章详细讨论了如何将此问题转化为区间覆盖问题,并使用贪心算法求解,同时考虑了精度问题。
4145

被折叠的 条评论
为什么被折叠?



