您的位置:首页 > 产品设计 > UI/UE

1085. Perfect Sequence (25)

2016-02-21 14:36 375 查看
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

1、考察二分法

2、注意溢出(可以标志负数最大,也可以使用long long 解决)

#include<iostream>
#include<algorithm>
using namespace std;
int a[1000005],n,p;
int find(int l,int t){
int r=n-1;
if(t<0)//溢出
return r;
while(r!=l){
int mid=(r+l)/2;
if(a[mid]>=t)
r=mid;
else l=mid+1;
}
while(a[r]>t)
r--;
return r;
}
int main(){
cin>>n>>p;
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
int maxl=0;
for(int i=0;i<n;i++)
{
int M=a[i]*p;
int k=find(i,M);
maxl=max(k-i+1,maxl);
}
cout<<maxl<<endl;
return 0;
}


使用long long解决

#include<iostream>
#include<algorithm>
using namespace std;
long long a[1000005],n,p;
int find(long long l,long long t){
int r=n-1;
while(r!=l){
int mid=(r+l)/2;
if(a[mid]>=t)
r=mid;
else l=mid+1;
}
while(a[r]>t)
r--;
return r;
}
int main(){
freopen("in.txt","r",stdin);
cin>>n>>p;
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
int maxl=0;
for(int i=0;i<n;i++)
{
long long M=a[i]*p;
int k=find(i,M);
maxl=max(k-i+1,maxl);
}
cout<<maxl<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: