poj 3069 Saruman's Army (贪心)
简单贪心。
从左边开始,找 r 以内最大距离的点,再在该点的右侧找到该点能覆盖的点。如图。

自己的逻辑有些混乱,最后还是参考书上代码。(《挑战程序设计》 P46)
/******************************************
Problem: 3069 User:
Memory: 668K Time: 16MS
Language: G++ Result: Accepted
******************************************/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int a[1005];
int main()
{
int r, n, i;
while (scanf("%d%d", &r, &n) == 2) {
if (r == -1) break;
for (i = 0; i < n; ++i)
scanf("%d", &a[i]);
sort(a, a + n);
int ans;
ans = i = 0;
while(i < n) {
int s = a[i++]; // s is the first point uncovered
while (i < n && a[i] <= s + r) ++i; // s can cover range
int p = a[i - 1]; // p should be covered
while (i < n && a[i] <= p + r) ++i; // p can cover range
++ans; // the point is p
}
printf("%d\n", ans);
}
return 0;
}
浙公网安备 33010602011771号