1085 Perfect Sequence (排序)
1085 Perfect Sequence (25 分)
Given a sequence of positive integers and another positive integer p. The sequence is said to be a perfect sequence if M≤m×p where M and m are the maximum and minimum numbers in the sequence, respectively.Now given a sequence and a parameter p, you are supposed to find from the sequence as many numbers as possible to form a perfect subsequence.
Input Specification:
Each input file contains one test case. For each case, the first line contains two positive integers N and p, where N (≤105 ) is the number of integers in the sequence, and p (≤109) is the parameter. In the second line there are N positive integers, each is no greater than 109
Output Specification:
For each test case, print in one line the maximum number of integers that can be chosen to form a perfect subsequence.
Sample Input:
10 8
2 3 20 4 5 1 6 7 8 9
Sample Output:
8
題目大意
給定一個序列A和引數p,若序列A中最大值為M,最小值為m,滿足M<=m*p,則稱序列A為perfect sequence;依據這個定義,題目要求在給定的序列中找出儘可能多的元素組成一個新的序列,使得這個序列為perfect sequence。
分析
尋找序列極值問題,若對演算法的複雜度無苛刻要求,可先對序列排序,定義當前最大寬度maxwidth,遍歷序列,遍歷過程中以當前maxwidth為起始寬度尋找比maxwidth更大寬度的序列。另外,題目中序列元素和引數p的範圍均為0~109,兩數想成數的範圍將可能超過109,因此將數的型別定義為long int
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v;
int main(){
long long n,p;
cin>>n>>p;
v.resize(n);
for(int i=0;i<n;i++) cin>>v[i];
sort(v.begin(), v.end());
int maxwidth=1;
for(int i=0;i<n;i++){
while(i+maxwidth-1<n && v[i+maxwidth-1]<=p*v[i]) maxwidth++;
}
cout<<maxwidth-1;
}