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,那么就按自己写的来排序。


posted @ 2015-05-31 19:56  Herumw  阅读(331)  评论(0编辑  收藏  举报