今日头条笔试题 数列

/*
    树状数组维护
    先以A对排序
    树状数组维护i以后的比y的个数
*/
#include
#include
#include
using namespace std;
const int maxn = 100000+10;
struct node {
    int x, y, pos;
    bool operator < (const node &a) const {
        if (x == a.x)
            return yy;
        return xx;
    }
}p[maxn], q[maxn];
int A[maxn];
int B[maxn];
int lowbit(int i) {
    return i&(-i);
}

void add(int a, int i) {
    while (i<=maxn-1) {
        A[i] += a;
        i += lowbit(i);
    }
}

int sum(int i) {
    int res = 0;
    while (i >= 1) {
        res += A[i];
        i -= lowbit(i);
    }
    return res;
}


int main() {
    int n, m;
    cin>>n>>m;
    for (int i=0; i"%d", &p[i].x);
    for (int i=0; i"%d", &p[i].y);

    sort(p, p+n);

    for (int i=0; i<m; i++) {
        scanf("%d%d", &q[i].x, &q[i].y);
        q[i].pos = i;
    }

    for (int i=0; i1, p[i].y);

    sort(q, q+m);

    int k = 0;

    for (int i=0; iif (p[i].x < q[k].x)
            add(-1, p[i].y);
        else {
            while (1) {
                B[q[k].pos] = sum(maxn-1)-sum(q[k].y-1);
                k++;
                if (k >= m)
                    break;

                if (p[i].x < q[k].x) {
                    add(-1, p[i].y);
                    break;
                }
            }
        }
        if (k >= m)
            break;
    }

    for (int i=0; i<m; i++)
        printf("%d\n", B[i]);
    return 0;
}

你可能感兴趣的:(笔试题)