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<iostream>
#include<vector>
#include<algorithm>

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值