PAT 1085 Perfect Sequence(25 分)(二分)

Given a sequence of positive integers and another positive integer p. The sequence is said to be a perfect sequence if M≤m×pwhere 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 (≤10​5​​) is the number of integers in the sequence, and p (≤10​9​​) is the parameter. In the second line there are N positive integers, each is no greater than 10​9​​.

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

题解:题目定义了完美序列,需要满足以下条件,该序列的最大值小于等于该序列最小值跟p的乘积,而且题目还要求使序列的长度尽可能长,则说明找到的完美序列长度应该包含是在题目给出序列找出满足条件最小值和最大值的长度(有点难以表达),可以用二分法做。

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int a[maxn];
int main()
{
    int n,p;
    int ans=0;
    cin>>n>>p;
    for(int i=0;i<n;i++)
        cin>>a[i];
    sort(a,a+n);
    for(int i=0;i<n;i++)
    {
        int j=upper_bound(a+i+1,a+n,(long long)a[i]*p)-a;
        ans=max(ans,j-i);
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42671353/article/details/82252997