跳到正文

个人记录

B2167 查找最后一个出现的位置

clki约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月24日
更新
2025年12月24日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

先读题:

输入一个长度为 n 的非递减正整数数列 a 1 ​ ,a 2 ​ ,…,a n ​ ,然后进行 m 次询问。对于每次询问,给出一个整数 q,要求输出这个数字在序列中最后一次出现的下标。如果序列中不包含该数字,请输出 −1 。

注意:下标从 1 开始。

这不就是upper_bound的模板吗?

C++
#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;
}
原文