【PAT】1085. Perfect Sequence (25)【双指针算法(尺取法)】

本文介绍了一种通过排序和尺取法求解完美数列的问题。对于给定的数列和参数p,需要找到尽可能多的数来形成一个完美子数列,即数列中的最大值不超过最小值乘以p。通过示例输入输出展示了如何实现这一算法。

题目描述

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.

翻译:给你一个正整数数列和另一个正整数p。当M(数列的最大值)<=m(数列的最小值)*p,那么这个数列就叫做完美数列。
现在给你一个数列和一个参数p,你需要找出当前数列中尽可能多的数来组成一个完美数列。

INPUT FORMAT

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.

翻译:每个输入文件包含一组测试数据。对于每组输入数据,第一行包括两个正整数N和p,N(<=10^5)代表数列中的数字数,p(<=10^9)为参数。第二行包括N个正整数,每一个都不超过10^9。

OUTPUT FORMAT

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


解题思路

这道题可以先排序,再用尺取法解决。由于后面的值总是大于等于前面的值,我们可以通过不断推进前指针和后指针,计算出它们的最大距离,直到指针到达数列末尾为止。注意输入的数字可能为long long int,不知道为什么,比较坑。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;
int N,p;
long long int d[100010]; 
int main(){
    scanf("%d%d",&N,&p);
    for(int i=0;i<N;i++)scanf("%lld",&d[i]);
    sort(d,d+N);
    int sum=1,pre=0,pro=1;
    while(pre<N&&pro<N){
        long long int temp=d[pre]*p;    
        if(d[pro]<=temp)pro++;
        else{
            sum=max(sum,pro-pre);
            pre++;
        }
        if(pro==N){
            sum=max(sum,pro-pre);
            pre++;  
        }
    }
    printf("%d\n",sum);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值