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’.
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
思路:
贪心与动态规划。
首先是确定什么样的sprinklers符合题意。下面是我在网上找到的一张图。
大致需要判断的有以下三个方面:
- 起始位置是否小于0;
- 中间是否存在空隙;
- 最终位置是否超过l。
中间是需要寻找最优解的(最少),所以用last标记(写的时候没有考虑到)。
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef double D;
const int N=1e4+5;
int n;
D l,w;
struct node
{
D left,right;
}a[N];
D gougu(D r)
{
return sqrt(r*r-(w/2)*(w/2));
}
bool cmp(node x,node y)
{
return x.left <y.left ;
}
int main()
{
while(scanf("%d %lf %lf",&n,&l,&w)!=EOF)
{
D o,r;
for(int i=1;i<=n;i++)
{
scanf("%lf %lf",&o,&r);
if(r<w/2)
{
a[i].left =a[i].right =0;
}
else
{
a[i].left =o-gougu(r);
a[i].right =o+gougu(r);
}
}
sort(a+1,a+n+1,cmp);
// for(int i=1;i<=n;i++)
// printf("%lf %lf\n",a[i].left ,a[i].right );
D st=0,ed=0;
int last=0,ans=0;
while(ed<l&&last<=n)
{
for(int i=last+1;i<=n;i++)//找到下一个的最优解,即右端最大处
{
if(a[i].left <=st)
{
if(a[i].right >ed)
{
last=i;
ed=a[i].right ;
}
}
else
break;
}
if(st==ed)//下一个没找到
{
ans=-1;
break;
}
st=ed;
ans++;
// printf("ans=%d last=%d\n",ans,last);
}
if(last>n)
printf("-1\n");
else
printf("%d\n",ans);
}
return 0;
}