Saruman‘s Army
直线上有N个点。点i的位置是X[i]。从这N个点中选择若干个,给他们加上标记。对于每一个点,距离其R以内的区域里必须有带有标记的点(自己本身带有标记,可以认为与其距离为0的地方有一个带有标记的点)。在满足这个条件的情况下,希望能为尽可能少的点添加标记。请问至少需要标记几个点?
limit:
1<=N<=1000
0<=R<=1000
0<=Xi<=1000
Input:
0 3
10 20 20
10 7
70 30 1 7 15 20 50
-1 -1 //结束输入的标志
Output:
2
4
这是一条很典型的贪心问题。对于每一个点,其R的范围内必须有一个带有标记的点,带有标记的点必须在其右。我们只需要从左不断扩大R就行了,必须尽可能覆盖到更右的地方,取的点就可以尽量少。
#include<iostream>
#include<algorithm>
using namespace std;
int x[1005];
void solve(int n,int r)
{
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;
}
int main()
{
int n,r;
while (cin>>r>>n && n!=-1)
{
for (int i=0; i<n; i++)
cin>>x[i];
solve(n,r);
}
return 0;
}