给定一个正整数数列,和正整数 p,设这个数列中的最大值是 M,最小值是 m,如果 M≤mp,则称这个数列是完美数列。
现在给定参数 p 和一些正整数,请你从中选择尽可能多的数构成一个完美数列。
输入格式:
输入第一行给出两个正整数 N 和 p,其中 N(≤10
5
)是输入的正整数的个数,p(≤10
9
)是给定的参数。第二行给出 N 个正整数,每个数不超过 10
9
。
输出格式:
在一行中输出最多可以选择多少个数可以用它们组成一个完美数列。
输入样例:
10 8
2 3 20 4 5 1 6 7 8 9
输出样例:
8
思路:从数据的规模来看暴力肯定是会超时的,于是我就想到了开辟两个数组,一个数组v1存放原始数据,另一个存放v2乘p之后的数据。然后对数组进行排序,紧接着就用二分法在v1数组中找v2中元素所在的位置,找到的位置肯定是大于等于v2数组中的元素,我们想要的是第一个大于该元素的位置,然后减去这个数在原数组中的位置就是完美数列的的长度。要把数据都初始成long long的!最终的时间复杂度就是nlogn。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
typedef long long ll;
vector<ll>v1;
vector<ll>v2;
ll n,p,res = 1;
ll Find(ll vel)
{
ll l=0,r=n;
while(l < r)
{
ll mid = (l+r) >> 1;
if(v1[mid] == vel)
return mid+1;
else if(v1[mid] > vel)
r = mid - 1;
else l = mid + 1;
}
return l;
}
int main()
{
cin>>n>>p;
if(n == 0)
{
cout<<"0";
return 0;
}
ll a;
for(int i=0;i<n;i++)
{
scanf("%d",&a);
v1.push_back(a);
}
sort(v1.begin(),v1.end());
for(int i=0;i<n;i++)
v2.push_back(v1[i]*p);
//在v1中查找v2所在的位置
for(int i=0;i<n;i++)
{
ll pos = Find(v2[i]);
// cout<<v2[i]<< " "<< pos<<endl;
while(pos < n && v1[pos] <= v2[i])
pos++;
res = max(res,pos-i);
}
cout<<res;
}