题目
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)。