PAT B1030/A1085 完美数列

1085 Perfect Sequence
分数 25
作者 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 (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

分析:本题考虑将序列排序后操作,可以采用单指针和二分查找来确定范围,也可以采用双指针确定范围。显然地,如果子数列a(i,j)符合要求,那么a(i+1,j)也符合要求,因此查找从a[i+1]开始的完美数列可以利用a[i]的结果。这样题目的复杂度降低到线性。如果每次查找都从当前元素开始,则复杂度会超时。

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
	long num;
	long long p, temp;
	vector<int> array;
	cin >> num >> p;
	for (int i = 0;i < num;i++) {
		cin >> temp;
		array.push_back(temp);
	}
	sort(array.begin(), array.end());
	int length = array.size();
	int left = 0, right = 0,maxnum = 0;
	while (left < length&&right<length) {
		while (array[right] <=(long long)( p * array[left])&&right<length) {
			//即使左指针前进,左右之间的序列也一定是符合要求的,因此可以将复杂度降低到线性
			//注意指针的越界问题,可能导致段错误
			//由于 p * array[left]可能超出int范围,因此需要转换类型
			if (right - left + 1 > maxnum)
				maxnum = right - left + 1;
			right++;
		}
		left++;//左指针前移
	}
	cout<< maxnum << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值