【CodeForces 600B 】Queries about less or equal elements(二分查找)

Description

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.

Sample Input

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

题目大意

题意很简单,两个数n,m分别表示a,b中数的个数,接着给你两个串a[n],b[m],求a中有几个数比b[i]小,最后输入结果

思路

这题不了解二分查找可能会直接暴力,但是这样做肯定超时,可以自己手写二分,也可以调用STL库中的upper_bound 或者 lower_bound函数,我是自己手写了一个二分查找,感觉对于理解二分的思想还是有一定好处的。
关于upper_bound & lower_bound可以见:
http://baike.baidu.com/link?url=-ieIhOaHE-SbeSxl9ybtXqKY_DrZWaovz6fMf4b-QECJAmh_f8JQKzYsi2cujM7Jb7Ifa4JyoIbbDWbFXVzb5a

代码

#include 
#include 
#include 
#include 

using namespace std;

const int maxn=2*1e5+5;

long long int a[maxn],b[maxn],n,m,ans[maxn];

int part(int sta,int end,int pos)
{
    if(pos>=a[n]) return n;
    if(pos1]) return 0;
    long long int mid=(sta+end)/2;
    if(a[mid-1]<=pos&&a[mid]>pos) 
    {
        return mid-1;
    }
    if(a[mid+1]>pos&&a[mid]<=pos)
    {
        return mid;
    }
    if(a[mid]>pos)
    {
        end=mid;
        return part(sta,end,pos);
    }
    else if(a[mid]<=pos)
    {
        sta=mid;
        return part(sta,end,pos);
    }

}

int main()
{
    while(~scanf("%lld %lld",&n,&m))
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%lld",&a[i]);
        }
        for(int i=1;i<=m;i++)
        {
            scanf("%lld",&b[i]);
        }
        sort(a+1,a+1+n);
        for(int i=1;i<=m;i++)
        {
            ans[i]=part(1,n,b[i]);
        }
        for(int i=1;i<=m;i++)
        {
            if(i==1) printf("%lld",ans[i]);
            else printf(" %lld",ans[i]);
        }
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(ACM)