二分法
#include <cstdio>
#include <cstring>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
typedef long long LL;
int main(){
LL N, p, a, i, left, right,mid,maxn=0;
set<LL> sets;
for(i=0; i<N; i++){
scanf("%ld",&a);
sets.insert(a);
}
set<LL>::iterator it=sets.begin();
int n = sets.size();
for(i=0; i< n; i++){
left=i;
right=n-1;
int m=*(it+i);
//[Error] no match for 'operator+' (operand types are 'std::set<long long int>::iterator {aka std::_Rb_tree_const_iterator<long long int>}' and 'LL {aka long long int}')
if(*(it+right) <= m*p){
maxn=right-i+1>maxn?right-i+1:maxn;
continue;
}
while(left<right){
mid=(right-left)/2+left;
if(*(it+mid) <= m*p){
left=mid+1;
}else{
right=mid;
}
}
maxn=left-i+1>maxn?left-i+1:maxn
}
printf("%d",maxn);
return 0;
}
two pointer
#include <cstdio>
#include <vector>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <iostream> //用set试试
using namespace std;
typedef long long LL;
bool cmp(LL a, LL b){
return a<=b;
}
int main(){
vector<LL>vec;
LL a, p;
int N, i, mid, p1, p2, maxn=0;
cin >> N >>p;
for(int i=0; i<N; i++){
cin >> a;
vec.push_back(a);
}
sort(vec.begin(),vec.end(),cmp);
int len=vec.size();
for(p1=0; p1<N; p1++){
LL c = vec[p1]*p;
for(p2 =p1+maxn; p2<N;){
//P2和P1的初始距离至少要比已经求得的距离大
if(vec[p2]<=c){
p2++;
}else break;
}
maxn=max(maxn,p2-p1);
if(len-p1+1<maxn) break;
}
printf("%ld",maxn);
return 0;
}
转载须注明出处