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 9Sample Output:
8
找出符合题目给出的条件的最长子序列,输出其长度。首先先对序列排序,这样可以很方便的直到子序列的最大最小值。设定两个索引值代表子序列的左右端,首先增大右端索引,直到不满足条件,求得现在的子序列长度,这个子序列肯定是左端索引为当前值时符合题目条件的最长子序列,然后更新最终答案,然后增大左端索引直到子序列满足条件,因为舍弃掉的那部分在后面的循环中肯定也是不会符合条件的。然后就这样通过调整右端索引和左端索引来循环直到右端索引到达了序列的尾端。最后输出最终答案。注意要用long long型,因为相乘的过程中会产生比较大的数,会超过int的范围。
代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
long long m;
cin>>n>>m;
vector<long long>a(n);
for(int i=0;i<n;i++) cin>>a[i];
sort(a.begin(),a.end());
long long left=0,right=0;
long long Max=0;
while(true)
{
while(a[left]*m>=a[right]&&right<n) right++;
Max=max(Max,right-left);
if(right==n) break;
while(a[left]*m<a[right]&&left<right) left++;
}
cout<<Max;
}