Codeforces 600B Queries about less or equal elements 【离散化去重二分查找 + 树状数组】

来源:互联网 发布:极限挑战知乎话题 编辑:程序博客网 时间:2024/06/11 14:31

B. Queries about less or equal elements
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 athat 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 test(s)
input
5 41 3 5 7 96 4 2 8
output
3 2 1 4
input
5 51 2 1 2 53 1 4 1 5
output
4 2 4 2 5


小于等于号写成小于号,WA了一次。犯二了。


题意:给定一个由n个元素组成的序列a[]和一个由m个元素组成的序列b[],对每一个b里面的元素b[i],你需要统计出在序列a[]里面有多少个元素小于或者等于它。


思路:先用map存每个元素的个数,然后离散化去重。对去重后序列的每个元素,累加前面元素的个数。最后对于序列b里面的每个元素b[i],二分查找ID(根据排序方案处理,偷懒用了lower_bound o(╯□╰)o),这里需要判断返回ID对应的元素是否小于或者等于b[i]。因为感觉树状数组用的比较方便,就用了它来维护信息。



AC代码:


#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <algorithm>#include <queue>#include <stack>#include <map>#include <vector>#define INF 0x3f3f3f#define eps 1e-8#define MAXN (200000+10)#define MAXM (100000)#define Ri(a) scanf("%d", &a)#define Rl(a) scanf("%lld", &a)#define Rf(a) scanf("%lf", &a)#define Rs(a) scanf("%s", a)#define Pi(a) printf("%d\n", (a))#define Pf(a) printf("%.2lf\n", (a))#define Pl(a) printf("%lld\n", (a))#define Ps(a) printf("%s\n", (a))#define W(a) while(a--)#define CLR(a, b) memset(a, (b), sizeof(a))#define MOD 1000000007#define LL long long#define lson o<<1, l, mid#define rson o<<1|1, mid+1, r#define ll o<<1#define rr o<<1|1using namespace std;int a[MAXN], ans[MAXN];map<int, int> fp;int C[MAXN];int lowbit(int x){    return x & (-x);}void update(int x, int d, int n){    while(x <= n)    {        C[x] += d;        x += lowbit(x);    }}int sum(int x){    int s = 0;    while(x > 0)    {        s += C[x];        x -= lowbit(x);    }    return s;}int main(){    int n, m;    Ri(n); Ri(m); fp.clear();    for(int i = 1; i <= n; i++)        Ri(a[i]), fp[a[i]]++;    sort(a+1, a+n+1);    int R = 2;    for(int i = 2; i <= n; i++)        if(a[i] != a[i-1])            a[R++] = a[i];    sort(a+1, a+R); CLR(C, 0);    for(int i = 1; i < R; i++)        update(i, fp[a[i]], R-1);    for(int i = 0; i < m; i++)    {        int V; Ri(V);        int ID = lower_bound(a+1, a+R-1, V) - a;        if(a[ID] <= V)            ans[i] = sum(ID);        else            ans[i] = sum(ID-1);    }    for(int i = 0; i < m; i++)    {        if(i) printf(" ");        printf("%d", ans[i]);    }    printf("\n");    return 0;}


0 0