给定一个正整数数列,和正整数 p,设这个数列中的最大值是 M,最小值是 m,如果 M≤mp,则称这个数列是完美数列。
现在给定参数 p 和一些正整数,请你从中选择尽可能多的数构成一个完美数列。
输入格式:
输入第一行给出两个正整数 N 和 p,其中 N(≤105)是输入的正整数的个数,p(≤109)是给定的参数。第二行给出 N 个正整数,每个数不超过 109。
输出格式:
在一行中输出最多可以选择多少个数可以用它们组成一个完美数列。
输入样例:
10 8
2 3 20 4 5 1 6 7 8 9
输出样例:
8
分析:
一开始我的解决方法很简单,排序后暴力,在符合条件的两数之间求出最大值。有两个测试点始终过不去,后来想了另外一种方法,也是两层for循环,还是过不去。后来换成了现在的代码,虽然也是循环中套循环,但是过了超时的测试点。基本思路就是head,tail作为指针从数组头尾开始移动,判断指针在什么条件下移动。我这里是在head和tail两个点上探测的,从而决定谁去移动。
最后一个测试点是找博客才知道,如果想的话可能想破头也猜不到吧……这个坑就是m * p超过了整数的范围,所以把p定义成了long类型。我真是……见识短!
附自己的代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int N, temp, length;
long p;
int head, tail;
vector<int> num;
cin >> N >> p;
for(int i = 0; i < N; i++){
scanf("%d", &temp);
num.push_back(temp);
}
sort(num.begin(), num.end());
head = 0;
tail = num.size() - 1;
length = tail - head + 1;
while(num[tail] > num[head] * p){
int step = tail - head;
while(step >= 1){
if(num[head + step] <= num[head] * p && num[tail] <= num[tail - step] * p){
length = step + 1;
printf("%d", length);
return 0;
}
//左移
if(num[head + step] <= num[head] * p){
tail--;
length = tail - head + 1;
break;
}
//右移
if(num[tail] <= num[tail - step] * p){
head++;
length = tail - head + 1;
break;
}
step--;
if(step == 0) head++;
}
}
printf("%d", length);
}
说实话,这段代码虽然过了测试点但还是挺慢的。在网上找到了一位大神的代码,对比之下,高下立判:
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int N, a[100000], prelen = 1, nxtlen;
long p;
scanf("%d %d", &N, &p);
for(int i = 0; i < N; i++)
scanf("%d", a + i);
sort(a, a + N);
for(int i = 0, nxtlen = prelen; i < N; i++){
if(a[i] <= a[i - prelen] * p)
nxtlen = prelen + 1;
else
nxtlen = prelen;
prelen = nxtlen;
}
printf("%d", prelen);
}
做法类似于求最大子序列和,快排O(NlogN),遍历O(N)。不仅效率高且代码十分简洁!佩服!