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

  1. The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the
    sizes of arrays a and b.
  2. The second line contains n integers — the elements of array a
    ( - 109 ≤ ai ≤ 109).
  3. 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的数组。对于第二个数组b j的每个元素,您应该找到数组a中小于或等于值b j的元素数。

输入
第一行包含两个整数Ñ,  米(1≤  Ñ,  米  ≤2·10 5) -的阵列的大小一个和b。

第二行包含Ñ整数-数组的元素一个( - 10 9  ≤  一个我  ≤10 9)。

第三行包含米整数-数组的元素b( - 10 9  ≤  b Ĵ  ≤10 9)。

输出
打印用空格分隔的m个整数:第j个元素等于数组a中小于或等于值b j的元素个数。

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>

using namespace std;
int main()
{
    int n,m;
    long a[200086];
    long ans;
    while(cin>>n>>m)
    {
        for(int i=0;i<n;i++)
        {
            scanf("%ld",&a[i]);
        }
        sort(a,a+n);
        for(int j=0;j<m;j++)
        {
            scanf("%ld",&ans);
            long *it=upper_bound(a,a+n,ans);
            printf("%ld",it-a);
            if(j!=m-1)
                printf(" ");
            else
                printf("\n");
        }
    }
    return 0;
}

其实这道题的意义在于upper_boundlower_bound的用法而已。他们两个是使用的二分查找,效率比较高,需要注意的是他们的返回值是指针或者说是地址,所有我们在前面的接受出需要设立指针或者是一个iterator。然后我们求得是位置,减去数组的首地址就好了,就得到中间有多少个了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值