首页 > 其他分享 >二分模板

二分模板

时间:2023-02-16 23:45:16浏览次数:41  
标签:二分 PII int mid while include 模板

例题:AcWing 789. 数的范围

原题:

image

使用二分查找数值 \(x\) 的范围 \([l,r)\)。

注意:采用左闭右开的方式,这个时候返回右端点时会比最大编号多一,输出时要 \(-1\)。而求最小编号时不受影响。

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
using PII = pair<int, int>;

const int N = 100010;

int a[N];
int n, m;

PII query(int x) {
    int l = 0, r = n, res1 = 0;
    while (l < r) {
        int mid = l + (r - l) / 2;
        if (a[mid] >= x) r = mid;
        else l = mid + 1;
    }
    res1 = l;
    if (a[l] != x) return make_pair(-1, -1);
    
    l = 0, r = n;
    while (l < r) {
        int mid = l + (r - l) / 2;
        if (a[mid] <= x) l = mid + 1;
        else r = mid;
    }
    
    return make_pair(res1, l - 1);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    cin >> n >> m;
    for (int i = 0; i < n; i++) cin >> a[i];
    
    while (m--) {
        int x;
        cin >> x;
        PII res = query(x);
        cout << res.first << ' ' << res.second << '\n';
    }
    return 0;
}

标签:二分,PII,int,mid,while,include,模板
From: https://www.cnblogs.com/PlayWithCPP/p/17128704.html

相关文章

  • D. Moving Dots(组合数学,贡献,二分/双指针)
    题目https://codeforces.com/contest/1788/problem/D思路从题目给的“2”这个信息入手,从贡献这个方面来考虑对于任意两不同的点,具有一定的范围,让这个范围内的点都被......
  • 2.二分查找新方法
    2.二分查找目录2.二分查找2.1新方法2.2例子162.寻找峰值2.1新方法近日重写二分查找的算法题还是倍感疑惑,在边界问题上还是有问题。在B站学习的时候,学到了一种新的理......
  • PHP 之自定义模板解析
    一、解析列表1、效果图 2、示例代码<?phpinclude_once'parse.func.php';$data=array(array('scode'=>2,'link'=>'https://www.b......
  • 模板的继承
    定义模板:layout.html{%loadstatic%}<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><linkrel="stylesheet"......
  • 服务端技术方案模板参考
    这是一个工程类技术方案模板,基于我之前的一些积累,适合相对独立的需求,实际开发中可以作为一个宽集,在这个基础上进行增加或者删减。一、概要很多时候,大家做项目的时候......
  • splay模板
    constexprintN=100005;//ch[i][0]代表左儿子,ch[i][1]代表右儿子intrt,tot,fa[N],ch[N][2],val[N],cnt[N],sz[N];structSplay{voidmaintain(intx......
  • 数论模板
    数学配合oiwiki:https://oi-wiki.org/math/位运算int__builtin_ffs(intx):返回x的二进制末尾最后一个1的位置,位置的编号从1开始(最低位编号为1)。当x为0时......
  • 基础二分查找
    二分查找力扣题目链接[704.二分查找-力扣(LeetCode)],给定一个 n 个元素有序的(升序)整型数组 nums和一个目标值 target ,写一个函数搜索 nums 中的target,如果目......
  • 代码随想录算法训练营 第一天 | 704. 二分查找,27. 移除元素
    二分查找心得:1,两种区间查找方式 第一种左闭右闭 关键有三点从0到length-1 边界取值left=mid+1或right=mid-1 查找条件是left<=right第二种左闭右开 ......
  • Python+Django(4):创建其他网页(模板继承)
    模板继承:1,修改主页父模板:抽取通用元素,在index.html同级目录下新建base.html<p><ahref="{%url'learning_logs:index'%}">LearningLog</a></p>{%blockcont......