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 wwith 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
题意:有一个l * w的草地,在草地的水平中心轴上,有n个喷水灭火装置,给出他们的所在的位置,和半径,问要覆盖这片草地,最少需要几个喷水装置。
题解:贪心区间覆盖问题,计算出每个装置所能覆盖的最大矩形的最左端和最右端,并记录下来,就成了一个裸的区间覆盖问题。
区间覆盖问题:先对小区间段的按左端大小进行排序,每次查找,衔接已经覆盖的区间且最大向右延伸距离的区间段,直到覆盖整个大区间,具体看代码注释。
最后附上AC代码
//#include<bits/stdc++.h>
//#include <unordered_map>
//#include<unordered_set>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<climits>
#include<queue>
#include<cmath>
#include<stack>
#include<map>
#include<string>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define MT(a,b) memset(a,b,sizeof(a))
const int INF = 0x3f3f3f3f;
const int O = 1e5;
const int mod = 1e9+7;
const int maxn = 1e4+5;
const double E = 2.718281828459;
const double PI = 3.141592653589;
struct dd{
double l; double r;
bool friend operator < (dd a, dd b){
return a.l == b.l ? a.r > b.r : a.l < b.l;
}
};
int main()
{
int n, l, w;
while(scanf("%d%d%d", &n, &l, &w)!=EOF)
{
dd a[maxn]; MT(a, 0);
int cnt = 0;
for(int i=0; i<n; i++)
{
int pos, r; scanf("%d%d",&pos, &r);
if(r <= 1.0 * w/2) continue; // 如果半径r没有w的一半大,则该装置没有用
double d = sqrt(1.0*r*r - 1.0*w*w/4);
a[cnt].l = pos - d;
a[cnt++].r = pos + d; //计算区间左端和右端
}
double pos = 0, t = 0; // pos表示已经覆盖区间的右端位置
//t表示一次while循环后的覆盖区间的右端位置(每次while循环查找得到一个最优的区间)
int k = 0, ans = 0; // k表示遍历的起点, 起优化作用
sort(a, a+cnt); //排序
while(pos < l) //当还未完全覆盖时继续循环
{
for(int i=k; i<cnt; i++) //遍历查找最优区间段
{
if(a[i].l <= pos) t = max(t, a[i].r); // 满足衔接条件,则更新t点
else { k = i; break; } // 因为区间段是按左端排序过的,所以遇到a[i].l > pos 时, 就可以退出了
}
if(pos == t) { ans = -1 ; break; } //没有查找到最优区间段,则无法完全覆盖
ans ++; //找到一个最优区间段,答案加一
pos = t; //更新pos点
}
printf("%d\n",ans);
}
return 0;
}