lower_bound()和upper_bound


函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,upper_bound()同理,只是返回大于val第一个元素位置。

所以,要记住:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置,且last的位置是越界的!

low_bount()返回查找元素的第一个可安插位置,也就是“元素值>=查找值”的第一个元素的位置.

普通数组(a[1],a[2]...,a[n])的写法是:j=upper_bound(a+1,a+1+n,b)-a;j是a[i]数组中第一个大于b的地址符。

另一种情况是如果定义结构体:

struct node{
int id,num;
}a[100006],q[100006];

如果这时用到upper_bound,如对于数字b,返回结构体a[i].num中第一个大于b的地址符,那么不能写成j=upper_bound(a+1,a+1+n,b)-a;

这里要把输入的数字存在结构体里,如上面写的q[100006],然后重载运算符‘<',比较的时候用j=upper_bound(a+1,a+1+n,p[i])-a;

整体写法如下:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
struct node{
	int id,num;
}a[100006],q[100006];
/*bool operator <(const node &q,const node &w)
{
	return q.num<w.num;
}两种写法都行,但上面这种快*/ 
bool operator<(node a,node b){
	return a.num<b.num;
}

int main()
{
	int n,m,i,j,k;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		map<int,int>hash;
		hash.clear();
		for(i=1;i<=n;i++){
			scanf("%d",&a[i].num);
			a[i].id=i;
			hash[a[i].num]++;
		}
		sort(a+1,a+1+n);
		for(i=1;i<=m;i++){
			scanf("%d",&q[i].num);
			if(hash[q[i].num]==0){
				printf("-1\n");continue;
			}
			else{
				hash[q[i].num]--;
				j=upper_bound(a+1,a+1+n,q[i])-a;
				printf("%d\n",a[j-1].id);
				for(k=j-1;k<=n-1;k++){
					a[k].id=a[k+1].id;
					a[k].num=a[k+1].num;
				}
				n--;
			}
		}
	}
	return 0;
}



还有一点,就是运算符定义后,排序时如果不加cmp,那么就按定义的运算符排序,如果自己再重新写一个cmp,那么就按自己写的来排序。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值