【贪心】Saruman's Army题解

一道贪心题。贪心的特点是找到局部最优解,做出当前的最好选择,且不能回退,只能一路往前。动态规划主要运用于二维或三维问题,而贪心一般是一维问题。

下面给出题目

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

 

Hint

In the first test case, Saruman may place a palantir at positions 10 and 20. Here, note that a single palantir with range 0 can cover both of the troops at position 20.

In the second test case, Saruman can place palantirs at position 7 (covering troops at 1, 7, and 15), position 20 (covering positions 20 and 30), position 50, and position 70. Here, note that palantirs must be distributed among troops and are not allowed to “free float.” Thus, Saruman cannot place a palantir at position 60 to cover the troops at positions 50 and 70.

大概题意就是有n支军队,现在有一种玩意(可视的小石头?),它的最大覆盖范围是R(可以理解成监控摄像头的最远可视距离),给出军队的位置坐标,要求用最少数目的小石头覆盖所有军队。

思路:

从最左边第一个没有被覆盖到的军队开始考虑,一路向右查找,找到可以覆盖它的最远的军队坐标,此处一定要放置一个小石头。再一路向右,找到该放置点不能覆盖到的第一个军队的坐标,再重复开始的过程。直到n个军队都被覆盖。

下面给出AC代码:

 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 int a[1001];
 6 
 7 int main(){
 8     int r,n,num;  //r:覆盖最大范围 n:军队数目
 9     while(cin>>r>>n && r!=-1 && n!=-1){
10         for(int i=0;i<n;i++){
11             cin>>a[i]; //输入军队坐标
12         }
13         sort(a,a+n);
14         int i = 0,num = 0;
15         while(i<n){
16             int s = a[i++]; //没有被覆盖的最左边的点
17             while(a[i]<=s+r)  ++i;  //一直向右走,直到刚好不能覆盖最左边的点的位置
18             int s2 = a[i-1]; //放置石头的点
19             while(a[i]<=s2+r) ++i;  //一直向右走,直到放置点刚好覆盖不到的位置
20             num++;
21         }
22         cout<<num<<endl;
23     }
24 
25     return 0;
26 }

猜你喜欢

转载自www.cnblogs.com/Aikoin/p/10073100.html
今日推荐