PAT_A 1085 Perfect Sequence & PAT_B 1030 完美数列

PAT_A 1085 Perfect Sequence & PAT_B 1030 完美数列

分析

题目定义了完美序列,即 \(m * p \geq M\) ,其中m表示序列中最小值,p为给定的参数,M为序列中最大值。要求在输入中找到最多的一组数组成目标数列,求目标数列的最大长度。

考虑到输入中可能存在相同的元素,且输入的最小值不一定是目标数列的最小值。因此,考虑将排序后的输入从小到大依次作为最小值,寻找符合规定的最大值。经过尝试,顺序寻找会有超时的风险,且排序后是递增有序的,因此改进为二分查找。

PAT_A 1085 Perfect Sequence

题目的描述

Given a sequence of positive integers and another positive integer p. The sequence is said to be a perfect sequence if Mm×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(≤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

PAT_B 1030 完美数列

题目的描述

给定一个正整数数列,和正整数 p,设这个数列中的最大值是 M,最小值是 m,如果 Mm**p,则称这个数列是完美数列。

现在给定参数 p 和一些正整数,请你从中选择尽可能多的数构成一个完美数列。

输入格式:

输入第一行给出两个正整数 Np,其中 \(N(≤10^5)\)是输入的正整数的个数,\(p(≤10^9)\)是给定的参数。第二行给出 N 个正整数,每个数不超过 \(10^9\)

输出格式:

在一行中输出最多可以选择多少个数可以用它们组成一个完美数列。

输入样例:

10 8
2 3 20 4 5 1 6 7 8 9

输出样例:

8

AC的代码

#include<bits/stdc++.h>

using namespace std;

int main(){
    int N, ans=0;
    cin>>N;
    long long p;
    vector<long long> num(N);
    cin>>p;
   for(int i=0;i<N;i++){
       cin>>num[i];
    }
    sort(num.begin(),num.end());
    int lower=0;
    while(lower+ans<N){
        while(lower>0&&num[lower]==num[lower-1]&&lower+ans<N)lower++;
        long long tmax = p * num[lower];
        int upper = lower +1;

        while(upper<N&&num[upper]<=tmax){
            upper = (upper+N+1)/2;
        }
        while(upper>N-1||num[upper]>tmax)upper--;
        
        //如果每次按顺序搜索会有超时的可能
//         while(upper<N&&num[upper]<=tmax)upper++;
        if(upper-lower + 1>ans){
            ans = 1 + upper-lower;
        }
        lower++;
    }
    cout<<ans<<endl;
    return 0;
}
posted @ 2022-09-14 18:29  ghosteq  阅读(20)  评论(0编辑  收藏  举报