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.
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).
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.
5 4 1 3 5 7 9 6 4 2 8
3 2 1 4
5 5 1 2 1 2 5 3 1 4 1 5
4 2 4 2 5
题目分析:该题是一种数组类的题,要求根据数组a、b给出数组b中每一个数在数组a中不小于其的个数。如果仅仅是排序后查找的话肯定会超时。可以考虑二分查找。二分查找的目的是找到那个正好可以放下那个数并且不会改变数组有序性的位置。在此给出两种解决方案。
第一种为手写二分法,见AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
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(pos<a[1]) 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;
}
第二种方案使用的是STL中的已经定义好的函数:upper_bound函数,见AC代码:
#include<stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=200005;
long long a[maxn],b[maxn],bnum[maxn];
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
scanf("%I64d",&a[i]);
for(int i=0; i<m; i++)
scanf("%I64d",&b[i]);
sort(a,a+n);
for(int i=0; i<m; i++)
bnum[i]= upper_bound(a,a+n,b[i])-a;
for(int i=0; i<m-1; i++)
printf("%I64d ",bnum[i]);
printf("%I64d\n",bnum[m-1]);
}
upper_bound函数,具体使用方法简单易懂,可参考:http://blog.sina.com.cn/s/blog_62582b7e0100eyqz.html。
看来STL真是个非常方便实用的函数库,以后得多多接触学习。
特记下,以备后日回顾。