C/-d D

来源:互联网 发布:淘宝的所在地怎么修改 编辑:程序博客网 时间:2024/05/29 17:51

呀吧  可算是a掉了

补得题,可算是懂得题目是啥意思了,就是最少包含范围,在给定的数左右 r的范围内都是可以的覆盖的,

对于派出的兵,能够防守一个范围的,问最少守几个数


后来发现这其实也是一个贪心算法的例题

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 ofR 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 withinR units of some palantir.

Input

The input test file will contain multiple cases. Each test case begins with a single line containing an integerR, the maximum effective range of all palantirs (where 0 ≤R ≤ 1000), and an integern, the number of troops in Saruman’s army (where 1 ≤n ≤ 1000). The next line contains n integers, indicating the positionsx1, …,xn of each troop (where 0 ≤ xi ≤ 1000). The end-of-file is marked by a test case withR =n = −1.

Output

For each test case, print a single integer indicating the minimum number of palantirs needed.


Sample Input
0 310 20 2010 770 30 1 7 15 20 50-1 -1
Sample Output
24


#include <iostream>#include<algorithm>using namespace std;int army[1005];int main(){    int r,n;    while(cin>>r>>n&&(r!=-1&&n!=-1))    {   int num=0;        for(int i=0;i<n;i++)         cin>>army[i];         sort(army,army+n);         for(int i=0;i<n;)         {             int sum=0;             int mid=i;             int left=i;             while(i<n)             {                 if(army[mid]-army[left]>r)                    break;                 if(army[i]-army[mid]<=r)                 {                     i++;                 }                 else                {mid++;                }             }             num++;         }      cout <<num<< endl;    }    return 0;}

贪心算法:

从最左方开始,寻找范围内第一个节点,即驻扎点,标记后,再寻找右方新的第一个超出范围的点,然后重新开始

#include <iostream>#include<algorithm>using namespace std;int army[1005];int r,n;void solve(){    int i=0,ans=0;    while(i<n)    {        int s=army[i++];//第一个点的坐标,++后进入下一个点,其实等价于 s=army[i];i=i+1;        while(i<n&&army[i]<=s+r) i++;        int p=army[i-1];//此处不能忘了减一,因为此时的i已经超出了范围,需要减一        while(i<n&&army[i]<=p+r) i++;        ans++;    }    cout<<ans<<endl;}int main(){    while(cin>>r>>n&&(r!=-1&&n!=-1))    {   int num=0;        for(int i=0;i<n;i++)         cin>>army[i];         sort(army,army+n);         solve();    }    return 0;}


0 0
原创粉丝点击