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 | 0 3 |
Sample Output
1 | 2 |
Analysis
一条直线上有n个点,从n各点中选若干个加上标记,对于每一个点,距离其R以内的区域里必须有一个被标记的点,问至少有多少点需要加上标记。
根据贪心的思想,使用以下步骤:
- 从最左点开始,这个点右侧R距离以内的区域必须有一个被标记的点,那么就给距离其R以内的离它最远的点加上标记。
- 找到这个被标记点右侧R距离外最近的一个点。
- 将此点作为最左点,重复1、2,直到所有点都被覆盖。
Code
1 |
|