二分查找 A - Queries about less or equal elements

You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.

Input

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b.

The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109).

The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).

Output

Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.


给你两个整数数组a和b。对于第二个数组bj的每个元素,你应该找到数组a中小于或等于值bj的元素数量。输入第一行包含两个整数n,m ( 1≤n,m≤2105 )——数组a和b的大小第二行包含n个整数——数组a的元素( - . 109≤ai≤109 )。第三行包含m个整数——数组b的元素( - . 109≤bj≤109 )。输出由空格分隔的m个整数:其中的第j个等于数组a中小于或等于值bj的元素的数量。

 


题意即为:数组a有n个数,数组b有m个数,在a中找出小于等于每个b数的数量。


  思路:排序后用 二分法  upper_bound即可。


Examples

Input

5 4
1 3 5 7 9
6 4 2 8

Output

3 2 1 4

Input

5 5
1 2 1 2 5
3 1 4 1 5

Output

4 2 4 2 5

 


 


#include <bits/stdc++.h>
using namespace std;
vector<int> g;
vector<int> v;

int main()
{
    int n, m;
    cin>> n >> m;
   //输入n个数 即a[n],并且输入一个数,向不定长数组v的尾部添加一个;
    for(int i=0; i<n; i++) 
    {
        int tmp;
        cin>> tmp;
        v.push_back(tmp);
    }
   //输入m个数 即b[m],并且输入一个数,向不定长数组g的尾部添加一个;
    for(int i=0; i<m; i++)  //输入m个数 即b[m],并且输入一个数,向不定长数组g的尾部添加一个;
    {
        int tmp;
        cin>> tmp;
        g.push_back(tmp); 
    }
    sort(v.begin(), v.end());  //对不定长数组v 即a的所有数进行从小到大排列;
    int len = g.size();   //定义len为不定长数组g即b中的数的个数
    for(int i=0; i<len; i++)
    {
        if(i!=0)
            cout<< " ";
        cout<< upper_bound(v.begin(), v.end(), g[i]) - v.begin(); //看下文解释③!!!!!!!!
    }
    cout<<endl;
    
    
    return 0;
}

 


补充:

①   #include <bits/stdc++.h>   据说是 万能头文件...

    包含C++中包含的所有头文件,是C++版本升级:

    #include <iostream>
    #include <cstdio>
    #include <fstream>
    #include <algorithm>
    #include <cmath>
    #include <deque>
    #include <vector>
    #include <queue>
    #include <string>
    #include <cstring>
    #include <map>
    #include <stack>
    #include <set>

②  vector是STL的不定长数组,若a是vector;

    a.size() 读取它的大小;

    a.resize()改变大小;

    a.push_back()向尾部添加元素;

    a.pop_back() 删除最后一个元素;

 

③ 对于upper_bound来说,返回的是被查序列中第一个大于查找值的指针,也就是返回指向被查值>查找值的最小指针,lower_bound则是返回的是被查序列中第一个大于等于查找值的指针,也就是返回指向被查值>=查找值的最小指针。

 

lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值