Educational Codeforces Round 10 D. Nested Segments [离散化+树状数组]

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line.
Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide.
Output
Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment.
Examples
Input
Copy
4
1 8
2 3
4 7
5 6
Output
Copy
3
0
1
0
Input
Copy
3
3 4
1 5
2 6
Output
Copy
0
1
1

题解:题意大概就是给你几个区间,让你求某个区间内包含有的其他区间的个数.
哈哈,这道题我还天真的用暴力去写,当然,tle在第15个样例,
暴力不行,那我们就换其他方法,这里要用到 离散化 + 树状数组.
这里只要离散化一个端点即可,这里我是离散化了右端点.
然后把区间按左端点降序排序,位于上面的区间的区间肯定不包含在其底下的区间,所以我们接下来只要看右端点即可,

接下来就是要树状数组了,lowbit要来了,然后统计一下包含的右端点即可,具体看代码

#include <bits/stdc++.h>
const int N=2e5+5;
using namespace std;
struct seg{
    int l,r,id;
};
seg a[N];
int ans[N];
int d[N];
int sum[N];
bool comp(seg a,seg b){
    return a.l>b.l;
}
int lowbit(int x){
    return x&-x;
}
int query(int x){
    int ans=0;
    while(x>0){
        ans+=sum[x];
        x-=lowbit(x);
    }
    return ans;
}
int cnt=0;
void update(int x){
    while(x<=cnt){
        sum[x]++;
        x+=lowbit(x);
    }
}
int main()
{
    int n;

    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d%d",&a[i].l,&a[i].r);
        d[++cnt]=a[i].r;
        a[i].id=i;
    }
    sort(d+1,d+1+n);
    sort(a+1,a+1+n,comp);
    for(int i=1;i<=n;i++){
        int pos=lower_bound(d+1,d+1+n,a[i].r)-d;
        ans[a[i].id]=query(pos);
        update(pos);
    }
    for(int i=1;i<=n;i++) printf("%d\n",ans[i]);
    //cout << "Hello world!" << endl;
    return 0;
}

转载于:https://www.cnblogs.com/-yjun/p/10424502.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值