logo AlgoBeat OnlineJudge
登录 注册

#101. 【模板】二分 题解

作者: jiqihang  ·  发布于 2026-05-24 18:08:53  ·  最后修改于 2026-05-24 18:16:22
已通过
审核员:yuchangzhu 管理员 · 2026-05-24 18:16:22

思路

看题目和描述可知,本题为二分板子题。

正整数不下降序列确保了单调性。

求序列中大于某个数的最小整数,考虑 upper_bound,具体原因建议自学二分。

直接 upper_bound 找到 即可。

代码

#include<bits/stdc++.h>
using namespace std;
int n,a[100010],q;
int main()
{
    cin>>n>>q;
    for(int i=1;i<=n;i++) cin>>a[i]; 
    while(q--)
    {
        int x;
        cin>>x;
        int p=upper_bound(a+1,a+n+1,x)-a;
        if(a[p]<=x) cout<<-1<<endl;
        else cout<<p<<endl;
    } 
}

暂无评论

登录 后即可评论。