这是一个二分法做的题目, 二分法是一种非常常见的方法,时间复杂度为O(log(n)),非常实用, 这个题目的二分法可以手写, 也可以用stl的 upper_bound 函数代替。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, p, a[maxn];
typedef long long ll;
int binarysearch(int i, ll x) {
if (a[n - 1] <= x) return n;
int l = i + 1, r = n - 1, mid;
while (l < r) {
mid = (l+r) / 2;
if (a[mid] <= x) l = mid + 1;
else r = mid;
}
return l;
}
int main() {
cin >> n >> p;
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
int ans = 1;
for (int i = 0; i < n; i++) {
int j = binarysearch(i, (ll)a[i] * p);
ans = max(ans, j - i);
}
cout << ans;
return 0;
}
upper_bound
upper_bound() 函数定义在<algorithm>头文件中,用于在指定范围内查找大于目标值的第一个元素。该函数的语法格式有 2 种,分别是:
//查找[first, last)区域中第一个大于 val 的元素。
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,
const T& val);
//查找[first, last)区域中第一个不符合 comp 规则的元素
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, p, a[maxn];
typedef long long ll;
int main() {
cin >> n >> p;
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
int ans = 1;
for (int i = 0; i < n; i++) {
int j = upper_bound(a + i + 1, a + n, (ll)a[i] * p) - a;
ans = max(ans, j - i);
}
cout << ans;
return 0;
}