二分_1085 Perfect Sequence (25 分)

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

先将数组排序,枚举M,二分搜索搜索m即可解决

这里使用upper_bound存在问题,因为upper_bound是找到大于某个数的第一个位置,当存在等于的时候就会产生一定的问题,有两组样例过不去

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <set>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn = 1e5+100;
int n,p,a[maxn];

int _binary_search(double num)
{
    int l = 0,r = n-1;
    while(l <= r)
    {
        int mid = (l+r)>>1;
        if(a[mid] == num) return mid;
        if(a[mid] > num) r = mid-1;
        if(a[mid] < num) l = mid+1;
    }
    return l;
}
int main()
{
    scanf("%d%d",&n,&p);
    for(int i = 0;i < n;i ++)
        scanf("%d",a+i);
    sort(a,a+n);

    int ans = 0;
    for(int i = n-1;i >= 0;i --){
        int pos = _binary_search((double)a[i]/(double)p);
//        cout <<"M: "<<a[i] <<" m: "<< a[pos] <<" p: "<< p <<endl;
        if(ans < i-pos+1)
            ans = i-pos+1;
    }
    printf("%d\n",ans);
}

猜你喜欢

转载自blog.csdn.net/li1615882553/article/details/84592158