Saruman's Army--POJ3069

[C++]Saruman’s Army

Saruman’s Army:
直線上有N個點,點i的位置是Xi。從這N個點中選擇若干個,給它們加上標記。對每一個點,其距離爲R以內的區域裏必須有帶有標記的點(自己本身帶有標記的點,可以認爲其與距離爲0的地方有一個帶有標記的點)。在滿足這個條件的情況下,希望能爲儘可能少的點添加標記。請問至少要有多少點被加上標記?

輸入格式:
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.
輸出格式:
For each test case, print a single integer indicating the minimum number of palantirs needed.

輸入:
0 3
10 20 20
10 7
70 30 1 7 15 20 50
-1 -1
輸出:
2
4

解題思路:一個點的左右兩邊距離r以內的點都會被覆蓋,從最左邊的點看起(最左邊的點只需要管右邊有沒有點覆蓋它),找到與最左邊的點距離r以內的最遠的點。對該點加上標記,再找到對該標記點右邊距離r以內的最遠的點的下一個點,然後採用同樣的方法找到下一個標記點,如此重複操作

#include<iostream>
#include<algorithm>
using namespace std;

const int maxn = 10000;

int n;
int r;
int x[maxn];

int main(){ 
    
    while(cin>>r>>n){
        if(r == -1 && n == -1)
            break;
        for(int i = 0; i<n; i++){
            cin>>x[i];
        }
        sort(x, x+n);
        int ans = 0;
        int i = 0;
        while(i < n){
            int res = x[i++];
            while(i < n && x[i] <= res+r) i++;
            
            int p = x[i-1];
            ans++;
            
            while(i < n && x[i] <= p+r) i++;
        }
        
        cout<<ans<<endl;
    }   

    
    return 0;
}
發佈了45 篇原創文章 · 獲贊 6 · 訪問量 4866
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章