先读题:
输入一个长度为 n 的非递减正整数数列 a 1 ,a 2 ,…,a n ,然后进行 m 次询问。对于每次询问,给出一个整数 q,要求输出这个数字在序列中最后一次出现的下标。如果序列中不包含该数字,请输出 −1 。
注意:下标从 1 开始。
这不就是upper_bound的模板吗?
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 10;
int n,a[N],m;
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++)cin>>a[i];
while(m --){
int x;
cin>>x;
int pos = upper_bound(a + 1,a + 1 + n,x)- a - 1;
if(a[pos] != x)cout<<-1<<'\n';
else cout<<pos<<'\n';
}
return 0;
}