[PAT] Perfect Sequence

给定一个正整数序列和参数p,目标是找出能构成完美子序列的最大元素数量,满足序列中最大值不超过最小值的p倍。通过排序和双指针法解决此问题,算法复杂度为O(nlogn+n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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 (<= 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

 

给一个数字数组,给一个系数p,在数组中取尽量多的数组成集合A,使得A中最大值max和最小值min满足max <= min*p。返回A的规模。


分析

很简单,先把数组从小到大排序,用left、right两个指针扫描,left从0到n-1停止,right在left的循环内层,每次从left到n-1或遇到right > left * p停止。用tmp记录从当前left开始的perfect sequence的长度,maxSize记录最终结果。

特别地,如果某一次扫描中right到达了数组的左边界,此时的tmp一定是最大长度,直接输出就可以了。

要注意的是,p最大9位,2^31是10位,用int型的话,乘积溢出的风险很大,所以p要用long long型。


代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
	int n;
	long long p;
	scanf("%d%lld", &n, &p);
	vector<int> arr(n);
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
	}
	sort(arr.begin(), arr.end());
	int maxSize = 0, tmp = 0;
	for (int left = 0; left < n; left++) {
		for (int right = left + maxSize; right < n; right++) {
			if (arr[right] <= arr[left] * p) {
				tmp = right - left + 1;
				if (right == n - 1) {
					printf("%d", tmp);
					return 0;
				}
				maxSize = tmp > maxSize ? tmp: maxSize;
			}
			else {
				break;
			}
		 }
	}
	printf("%d", maxSize);
	return 0;
}

复杂度

代码写了两层循环,看起来像是个O(n^2)的算法。实际上,每次left移动后。right的扫描都是从left + maxSize开始的,而并非从left开始。也就是说,不论left移动还是right移动,right每次都要向右移动一步,主算法复杂度O(n)。

真正影响效率的是排序的O(nlogn)。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值