有关lower_bound的比较函数

如果自己实现lower_bound的功能无疑是用二分实现。

所以,lower_bound可以通过自定义比较函数来实现多种算法。

比如,在一串数中找出比x大的数

比较函数cmp1是这样定义的

bool cmp1(int a,int b){return a<=b;}

int k=lower_bound(a+1,a+1+n,x,cmp1}-a;

通过以上例子,可以明白比较函数中所要确定的范围的补集为true。

蒟蒻表示就知道这么点。。

我们来看一道题:

bzoj1609题目

这道题我们可以用lower_bound求最长不降子序列(正反各求一遍,取最大值),时间复杂度O(NlogN)

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int n,a[30003],g[30003],ans;
int read()
{
	int x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}
bool cmp1(int a,int b){return a<=b;}
bool cmp(int a,int b){return a>=b;}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)a[i]=read();
    for(int i=1;i<=n;i++)g[i]=inf;
    for(int i=1;i<=n;i++)
    {
    	int k=lower_bound(g+1,g+1+n,a[i],cmp1)-g;
    	g[k]=a[i];
    	ans=max(ans,k);
    }
    for(int i=1;i<=n;i++)g[i]=-inf;
    for(int i=1;i<=n;i++)
	{
		int k=lower_bound(g+1,g+1+n,a[i],cmp)-g;
        g[k]=a[i];
		ans=max(ans,k);
	} 
	cout<<n-ans<<endl;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值