【PAT A1085】Perfect Sequence

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

示例代码

#include <cstdio>
#include <algorithm>
using namespace std;

int num[100010];

//二分查找
int biSearch(int begin, int end, long long target){
	//如果最后元素都比target小直接返回最后的位置
	if(target > num[end])
		return end;
	while(begin < end - 1){
		int mid = (begin + end) / 2;
		if(num[mid] <= target)
			begin = mid;
		else
			end = mid;
	}
	return begin;
}

int main(){
	int N, p;
	scanf("%d%d", &N, &p);
	for(int i = 0; i < N; i++)
		scanf("%d", &num[i]);
	
	sort(num, num + N);
	//begin和end用于二分查找,cnt为要求的最大数
	int begin = 0, end = N - 1, cnt = 0;
	//m是最小数,循环到N-cnt其实就可以了,因为再往后肯定比cnt小
	for(int m = 0; m < N - cnt; m++){
		//二分查找顺便更新查找的初始位置
		begin = biSearch(begin, end, (long long)num[m] * p);
		//如果有必要则更新cnt
		cnt = max(begin - m + 1, cnt);
	}
	printf("%d\n", cnt);

	return 0;
}
发布了30 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lvmy3/article/details/103975889