POJ 3069 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

0 3
10 20 20
10 7
70 30 1 7 15 20 50
-1 -1

Sample Output

2
4

题意:

直线上有N个点, 从这几个点中选取几个点加上标记, 对每个点, 其距离为R以内的区域里必须有带有标记的点。 请问至少有多少点被加上标记。

思路:

应该从最左边的s点开始搜寻距离s最远的小于r的点, 然后给它加上标记, 然后记下他的坐标d, 继续搜寻距离它r外最近的那个点, 以此类推。

代码如下:
 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=1005;
int a[maxn];
int r,n;
int main()
{
    while(scanf("%d%d",&r,&n)!=EOF&&(r!=-1||n!=-1))
    {
        int num=0;
        for (int i=0;i<n;i++)
              scanf("%d",&a[i]);
        sort(a,a+n);
        int i=0;
        while (i<n)
        {
            int s=a[i++];
            while (i<n&&a[i]<=s+r)
                    i++;
            num++;
            int d=a[i-1];
            while (i<n&&a[i]<=d+r)
                    i++;
        }
        printf("%d\n",num);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/81563539