PAT 1085. Perfect Sequence (25)(二分查找)

官网

1085. Perfect Sequence (25)

时间限制
300 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CAO, Peng
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.给出一列正整数和一个正整数p,尽可能选出多的数组成一个数列满足:M<=m*p,输出最长的个数即可,注意不是找子序列,感觉我做题做傻了啊。

解题思路

  • 1.先将原数列排序,i从第一个往最后一个遍历,找到不满足条件的那个j为止,然后对每个都求长度,最后求最大长度,但是直接j求会超时,要用二分法。
  • 2.注意int的范围。

AC代码

#include
#include
#include

using namespace std;

int main()
{
    int n, p;
    cin >> n >> p;
    vector<int> a(n);
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    sort(a.begin(), a.end());
    int maxlen = 0;
    //从i找到最后一个
    for (int i = 0; i < n; i++)
    {
        int l = i, r = n - 1;
        //二分法找
        while (r-l>1)
        {
            int mid = (l + r) / 2;
            if ((double)a[mid]/(double)p<=a[i])
            {
                l = mid;
            }
            else{
                r = mid;
            }
        }
        //强行不管l和r是什么,最后在看r行不行就可以了
        if ((double)a[r] / (double)p <= a[i])
        {
            l = r;
        }
        maxlen = max(l - i + 1, maxlen);
    }
    cout << maxlen << endl;
    return 0;
}

你可能感兴趣的:(PAT官网)