Bob is a skilled engineer. He must design a highway that crosses a region with few villages. Since this region is quite unpopulated, he wants to minimize the number of exits from the highway. He models the highway as a line segment S (starting from zero), the villages as points on a plane, and the exits as points on S . Considering that the highway and the villages position are known, Bob must find the minimum number of exists such that each village location is at most at the distance D from at least one exit. He knows that all village locations are at most at the distance D from S .
Input
The program input is from the standard input. Each data set in the file stands for a particular set of a highway and the positions of the villages. The data set starts with the length L (fits an integer) of the highway. Follows the distance D (fits an integer), the number N of villages, and for each village the location (x, y) . The program prints the minimum number of exits. White spaces can occur freely in the input. The input data are correct and terminate with an end of file.Output
For each set of data the program prints the result to the standard output from the beginning of a line.An input/output sample is in the table below. There is a single data set. The highway length L is 100, the distance D is 50. There are 3 villages having the locations (2, 4), (50, 10), (70, 30). The result for the data set is the minimum number of exits: 1.
Sample Input
100 50 3 2 4 50 10 70 30
Sample Output
1
先求出每个点个x轴的交点,注意交点可能超出去,超出去的就取边界点。每个点和x轴的交点构成一个区间,从最左边区间的右端点pos开始向左遍历,如果下一个区间包含了pos,则它们公用一个点,如果pos在下一个区间的外面,则出现了区间不相交的情况,点数就要增加了,此时再把pos设置为这个区间的右断点继续遍历。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset>
#include <cassert>
#include <cmath>
#include <functional>
using namespace std;
double L, D;
int n;
struct interval
{
double l, r;
interval(const double &x, const double &y) {
double R = sqrt(D * D - y * y);
l = max(x - R, 0.0);
r = min(x + R, L);
}
// 为了使用sort,所以这里重载定义了操作符<
bool operator<(const interval &x) const {
return r == x.r ? l > x.l : r < x.r;
}
};
vector<interval> inter;
int main()
{
ios::sync_with_stdio(false);
while (cin >> L) {
cin >> D >> n;
inter.clear();
double x, y;
for (int i = 0; i < n; i++) {
cin >> x >> y;
inter.push_back(interval(x, y));
}
sort(inter.begin(), inter.end());
int cnt = 1;
double pos = inter[0].r;
for (int i = 0; i < inter.size(); i++) {
if (pos <= inter[i].r && pos >= inter[i].l) {
continue;
}
// 当出现不相交的区间时,点数就要增加了
pos = inter[i].r;
cnt++;
}
cout << cnt << endl;
}
return 0;
}