题意:给定一系列的数字,对于这一系列的数字的某个字串中,假定最大的数为M,最小的数为m,参数p,满足M<=m*p,求这样字串中最长的字串有多少个
思路:首先对该序列按从小到大的顺序排序,然后使用二重循环进行遍历看是否满足条件,遍历如果直接使用二重循环暴力解的话,倒数第二个点会超时,所以我们在内层循环中直接从i+result开始找起,即从上一次计算出来的长度开始,因为要找的是最长的序列,所以即使重算从i到i+result的长度也不会超过之前算的长度,我们直接从i+result开始算起,如果有更长的则更新result,否则result就是最长的序列。
代码:
#include<iostream>
#include<algorithm>
#include<vector>
typedef long long int LL ;
using namespace std;
int main() {
LL n, p,result = 0,tem = 0;
cin >> n >> p;
vector<LL> v(n);
for (LL i = 0; i < n; i++)scanf("%lld", &v[i]);//输入数据
sort(v.begin(), v.end());//按从小到大开始搜索
for (LL i = 0; i < n; i++) {
for (LL j = i+result; j < n; j++) {
if (v[j] <= v[i] * p) {
tem = j - i + 1;
if (tem > result)result = tem;
}
else {
break;//只要出现大于情况则说明要退出了,
}
}
}
printf("%d\n", result);
system("pause");
return 0;
}