问题链接:POJ3069 Saruman's Army。
题意简述:直线上有N个点。点i的距离是Xi。从这N个点中选取若干点加上标记。对于每个点,与其距离为R的范围内必有做标记的点(包括自身)。求至少标记多少点才能满足要求。
问题分析:
这个问题可以用贪心法来解决。
先将各个点排序,从小到大顺序找必须标记的点,并且将其距离R以内的点排除。反复这个过程即可。
程序说明:(略)
AC的C++语言程序如下:
/* POJ3069 Saruman's Army */
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1000;
int a[N];
int solve(int n, int r)
{
int ans = 0, i = 0;
while(i < n) {
int start = a[i++];
// 遍历start范围内的点
while(i < n && a[i] <= start + r)
i++;
// 标记点计数,标记点
ans++;
start = a[i - 1];
// 遍历start范围内的点
while(i < n && a[i] <= start + r)
i++;
}
return ans;
}
int main()
{
int r, n;
while(cin >> r >> n && !(r == -1 && n == -1)) {
for(int i=0; i<n; i++)
cin >> a[i];
sort(a, a + n);
cout << solve(n, r) << endl;
}
return 0;
}