1030 完美数列 (25 分)
给定一个正整数数列,和正整数 p,设这个数列中的最大值是 M,最小值是 m,如果 M≤mp,则称这个数列是完美数列。
现在给定参数 p 和一些正整数,请你从中选择尽可能多的数构成一个完美数列。
输入格式:
输入第一行给出两个正整数 N 和 p,其中 N(≤105)是输入的正整数的个数,p(≤109)是给定的参数。第二行给出 N 个正整数,每个数不超过 109。
输出格式:
在一行中输出最多可以选择多少个数可以用它们组成一个完美数列。
输入样例:
10 8
2 3 20 4 5 1 6 7 8 9
输出样例:
8
思路: 直接做,就是枚举左端点, 找最大能达到的右端点,使得这个区间满足 M <= m*p ; 但是有个数据会超时, 所以考虑二分
在找能满足的最右端点时用二分取找 . 这样复杂度为 (n*long(n)) 。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <ctime>
#include <cmath>
using namespace std ;
const int MAX = 100005 ;
const int inf = 0x3f3f3f3f ;
typedef long long LL ;
LL a[MAX] ;
LL ret ;
LL n ,p;
int check(int i) {
if(a[n] <=ret ) return n ; // 剪枝 , 如果最长的满足,直接返回
LL left = i , right = n ; // 区间[i,n]
while(left <right) {
LL mid = (left+right)/ 2 ;
if(a[mid+1] <=ret) {
left = mid + 1 ;
}
else {
right = mid ;
}
}
return left ;
}
int main() {
cin >> n >> p ;
for(int i = 1 ; i<=n ; i++ ) {
scanf("%lld",&a[i]);
}
sort(a+1,a+1+n) ;
int cnt = 1 ;
for(int i = 1 ; i<=n ; i++ ) {
ret = p*a[i] ;
int j = check(i) ;
cnt = max(cnt,j-i +1) ;
}
cout<<cnt ;
return 0 ;
}
/*
10 8
2 3 20 4 5 1 6 7 8 9*/