最佳序列。
就是从给的序列里面,找最长的序列,满足最大值小于等于最小值*p
先给序列排序。从最小的开始,找能找到的最大值的位置,计算长度。
这里不能直接循环,会超时,需要二分查找,找小于等于理想值的位置。
关于二分查找贴个链接,讲了很细节的查找最后位置的各种方法。值得一看。
http://tianyanshentong.blog.51cto.com/3356396/1560237/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
long int n, p;
vector <int> seq;
int BinSerch(long int x ,int st, int ed) {
int low = st, high = ed;
while (low < high) {
int mid = (low + high + 1) / 2;
if (seq[mid] > x) {
high = mid - 1;
}
else
low = mid;
}
return low;
}
int main() {
cin >> n >> p;
seq.resize(n);
for (int i = 0; i < n; i++) {
scanf("%d", &seq[i]);
}
sort(seq.begin(), seq.end());
int pos = 0;
int max = 0;
int len = seq.size() - pos;
while (pos < seq.size() && len > max) {
long int pm = p * seq[pos];
int pos2 = BinSerch(pm, pos, seq.size() - 1);
if (pos2 - pos + 1 > max) {
max = pos2 - pos + 1;
}
pos++;
len = seq.size() - pos;
}
cout << max << endl;
return 0;
}