1085 Perfect Sequence (25分)
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 (≤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.
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
题目大意:
从n个正整数中选择若干个数,使得选择出的这些数中最大的值不超过最小值的p倍。问满足条件的选择方案中,选出的数最大个数。
解题思路:
由于题干中涉及到序列的最大和最小值,因此不妨先将所有的n个正整数从小到大进行排序。在此基础上证明:能使得选出的数个数最大的方案,一定是在该递增序列中选择连续的若干个数的方案。
于是问题转化为:在一个给定的递增序列中,确定一个左端点a[i]和一个右端点a[j],使得a[j]<=a[i]*p成立,且j-i最大。
如果强制进行O()的二重循环枚举,那么根据题目的数据范围,肯定是会超时的。这里有两种方法来解决这个问题:
二分法:
#include<iostream>
#include<algorithm>
using namespace std;
int n, p, arr[100010];
//在[i+1,n-1]范围内查找第一个大于x的数的位置
int binarySearch(int i, long long x)
{
if (arr[n - 1] <= x)
return n;
int l = i + 1, r = n - 1, mid;
while (l < r)
{
mid = (l + r) / 2;
if (arr[mid] <= x)
{
l = mid + 1;
}
else
{
r = mid;
}
}
return l;
}
int main()
{
cin >> n >> p;
for (int i = 0; i < n; i++)
cin >> arr[i];
sort(arr, arr + n);
int ans = 1;
for (int i = 0; i < n; i++)
{
//在a[i+1]~a[n-1]中查找第一个超过a[i]*p的数,返回其位置给j
int j = binarySearch(i, (long long)arr[i] * p);
ans = max(ans, j - i);
}
cout << ans << endl;
return 0;
}
当然,其中的二分查找可以用upper_bound()函数来代替,可以简化很多代码。
#include<iostream>
#include<algorithm>
using namespace std;
int n, p, arr[100010];
int main()
{
cin >> n >> p;
for (int i = 0; i < n; i++)
cin >> arr[i];
sort(arr, arr + n);
int ans = 1;
for (int i = 0; i < n; i++)
{
//在a[i+1]~a[n-1]中查找第一个超过a[i]*p的数,返回其位置给j
int j = upper_bound(arr + i + 1, arr + n, (long long)arr[i] * p) - arr;
ans = max(ans, j - i);
}
cout << ans << endl;
return 0;
}