CodeForces - 652D Nested Segments (树状数组 + 离散化)

题目链接

题意:

给 n 个区间,求每个区间包含多少子区间。

题解:

将每个区间的 r 存进树状数组里,然后对每个区间的 l 从大到小进行排序,每次查询时查的一定是比自己 l 大的,并且比自己 r 小的,即自己的子区间。由于数字比较大,需要离散化处理。

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<cstdlib>
#include<string>
#define INF 0x3f3f3f3f
#define MAXM 5000 + 10
#define MAXN 200000 + 10

using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;

int n;
struct node{
    int l, r;
    int id;
    bool operator < (const node &a) const{
        return l > a.l;
    }
}no[MAXN];
int tree[MAXN];

void add(int k, int num)
{
    while(k <= n){
        tree[k] += num;
        k += k & -k;
    }
}

int sum(int k){
    int ans = 0;
    while(k){
        ans += tree[k];
        k -= k & -k;
    }
    return ans;
}

int main()
{

    while(~scanf("%d", &n)){

        int a[MAXN], ans[MAXN];
        memset(tree, 0, sizeof(tree));

        for(int i = 1; i <= n; i ++){
            scanf("%d %d", &no[i].l, &no[i].r);
            no[i].id = i; a[i] = no[i].r;
        }

        sort(a + 1, a + n + 1);
        int k = unique(a + 1, a + n + 1) - (a + 1);
        for(int i = 1; i <= n; i ++)
            no[i].r = lower_bound(a + 1, a + k + 1, no[i].r) - (a + 1);

        sort(no + 1, no + n + 1);
        for(int i = 1; i <= n; i ++){
            ans[no[i].id] = sum(no[i].r + 1);
            add(no[i].r + 1, 1);
        }

        for(int i = 1; i <= n; i ++)
            printf("%d\n", ans[i]);
    }
}

/*

The WAM is F**KING interesting .

*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值