POJ 2481 树状数组

版权声明:欢迎转载,不要求署名~~~ https://blog.csdn.net/shadandeajian/article/details/82053726

传送门:题目

题意:

n个区间,求小区间被多少个大区间包含

题解:

我们可以按照r从大到小,l从小到大,把区间sort一遍,然后for循环,每次查找有多少个数在l的前面,就有多少个大区间包含此次遍历的区间,然后我们可以用树状数组记录一下,减少复杂度。

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define debug(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
using namespace std;

const int maxn = 1e5 + 10;
struct NODE {
    int l, r, id;
    bool operator<(const NODE& rhs)const {
        if (r == rhs.r)
            return l < rhs.l;
        return r > rhs.r;
    }
} node[maxn];
/********************树状数组模板************************/
int BITree_max;//数据范围[1,n]
int BITree_num[maxn];
void Update(int i, int value) { //更新结点i的值+=value
    while (i <= BITree_max) {
        BITree_num[i] += value;
        i += i & -i;
    }
}
int Query(int i) {//查询[1,n]的综合
    int ans = 0;
    while (i > 0) {
        ans += BITree_num[i];
        i -= i & -i;
    }
    return ans;
}
/********************树状数组模板************************/
int main(void) {
    ios::sync_with_stdio(false);
    int n;
    while (cin >> n && n) {
        memset(BITree_num, 0, sizeof BITree_num);
        int mmax = 0;
        for (int i = 1; i <= n ; i++)
            cin >> node[i].l >> node[i].r, ++node[i].l, ++node[i].r, node[i].id = i, mmax = max(mmax, max(node[i].l, node[i].r));
        BITree_max = mmax;
        int cnt[n + 1];
        sort(node + 1, node + 1 + n);
        for (int i = 1; i <= n; i++) {
            if (node[i].l == node[i - 1].l && node[i].r == node[i - 1].r)
                cnt[node[i].id] = cnt[node[i - 1].id];
            else
                cnt[node[i].id] = Query(node[i].l);
            Update(node[i].l, 1);
        }
        for (int i = 1; i <= n; i++)
            cout << cnt[i] << " \n"[i == n];
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shadandeajian/article/details/82053726