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的数组。对于第二个数组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_bound和lower_bound的用法而已。他们两个是使用的二分查找,效率比较高,需要注意的是他们的返回值是指针或者说是地址,所有我们在前面的接受出需要设立指针或者是一个iterator。然后我们求得是位置,减去数组的首地址就好了,就得到中间有多少个了。