PAT 乙级 c++ 完美数列 (25分)的两种常用方法

二分法

#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;
}

转载须注明出处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值