A 1085 Perfect Sequence
Problem Description
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
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
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
题目大意:
一个数字序列,最大的数是M,最小的数是m,给出一个数p。问从中最多取出多少个数组成一个序列,满足M≤m×p
解题思路:
先对输入的数字序列排序,然后设立下标r从后往前搜索,找到第一个符号条件的序列头下标l。此时以r为最大数的序列长度最长是(r-l+1)。
AC代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 100005;
ll a[maxn],p,now;
int n,ans=0;
int magic(ll x,int r){
int l=0,mid;
while(l<r){
mid=(l+r)/2;
if(a[mid]>=x){
r=mid;
}else{
l=mid+1;
}
}
return l;
}
int main(){
scanf("%d%lld",&n,&p);
for(int i=0;i<n;i++){
scanf("%lld",&a[i]);
}
sort(a,a+n);
int l=0,r=n-1;
while((r+1)>ans){ //如果从0开始计的最长长度都不比当前最长长度长,终止
l=0;
if(a[r]%p==0){
now=a[r]/p;
}else{
now=a[r]/p+1;
}
l=magic(now,r); //手写lower_bound函数,找到第一个满足条件的l的下标
ans=max(r-l+1,ans);
r--;
}
printf("%d",ans);
return 0;
}