倍增模板:【ybt高效进阶4-5-1】查找编号
题目大意:
给你一个单调不减序列,每次问你一个数在序列中最早出现的位置
思路:
这是一道二分查找的模板题,STL的
l
o
w
e
r
lower
lower_
b
o
u
n
d
bound
bound函数可以完美解决。当然,手写二分也是可行的
但是在这里我们用倍增来解决,当成模板题
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<vector>
#define r register
#define rep(i,x,y) for(r ll i=x;i<=y;++i)
#define per(i,x,y) for(r ll i=x;i>=y;--i)
using namespace std;
typedef long long ll;
const ll V=1e6+10;
ll a[V],n,now,p[50],x,m;
int main()
{
scanf("%lld%lld",&n,&m);
rep(i,1,n)
scanf("%lld",&a[i]);
rep(i,0,21)
p[i]=(ll)(1<<i);
while(m--)
{
now=0;
scanf("%lld",&x);
per(i,21,0)
if(now+p[i]<=n&&a[now+p[i]]<x)
now+=p[i]; //如果小于被查询数,每次加上2^k
if(a[now+1]!=x) printf("-1 ");
else printf("%lld ",now+1);
}
return 0;
}