Poj3069 Saruman's Army

Description

Saruman the White must lead his army along a straight path from Isengard to Helm’s Deep. To keep track of his forces, Saruman distributes seeing stones, known as palantirs, among the troops. Each palantir has a maximum effective range of R units, and must be carried by some troop in the army (i.e., palantirs are not allowed to “free float” in mid-air). Help Saruman take control of Middle Earth by determining the minimum number of palantirs needed for Saruman to ensure that each of his minions is within R units of some palantir.

Input

The input test file will contain multiple cases. Each test case begins with a single line containing an integer R, the maximum effective range of all palantirs (where 0 ≤ R ≤ 1000), and an integer n, the number of troops in Saruman’s army (where 1 ≤ n ≤ 1000). The next line contains n integers, indicating the positions x1, …, xn of each troop (where 0 ≤ xi ≤ 1000). The end-of-file is marked by a test case with R = n = −1.

Output

For each test case, print a single integer indicating the minimum number of palantirs needed.

Sample Input

1
2
3
4
5
0 3
10 20 20
10 7
70 30 1 7 15 20 50
-1 -1

Sample Output

1
2
2
4

Analysis

一条直线上有n个点,从n各点中选若干个加上标记,对于每一个点,距离其R以内的区域里必须有一个被标记的点,问至少有多少点需要加上标记。

根据贪心的思想,使用以下步骤:

  1. 从最左点开始,这个点右侧R距离以内的区域必须有一个被标记的点,那么就给距离其R以内的离它最远的点加上标记。
  2. 找到这个被标记点右侧R距离外最近的一个点。
  3. 将此点作为最左点,重复1、2,直到所有点都被覆盖。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int r, n;
int x[10000];
while (cin >> r >> n)
{
if (r == -1 && n == -1)
break;
memset(x, 0, sizeof(x));
for (int i = 0; i < n; i++)
{
cin >> x[i];
}
sort(x, x + n);
int i = 0, ans = 0;
while (i < n)
{
int s = x[i++];
while (i < n&&x[i] <= s + r)
i++;
int p = x[i - 1];
while (i < n&&x[i] <= p + r)
i++;
ans++;
}
cout << ans << endl;
}
return 0;
}