CF652 树状数组,离散化,子区间问题

D. Nested Segments
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard 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
4
1 8
2 3
4 7
5 6
output
3
0
1
0
input
3
3 4
1 5
2 6
output
0
1
1

http://codeforces.com/contest/652/problem/D

题目大意:

给n个区间,问,每个区间内有几个小区间(这些区间都是n个区间内的)。


思路:

由于坐标很大,但是n是2*100000,所以我们考虑离散化坐标。

首先,我们离散化所有的区间,然后我们用vector将所有的区间都包含在里面,排序后用二分对其全部都进行离散化。

接来下,我们以右端为基础,有树状数组来维护所有右端的值即可。

然后我们再以左端为主,然后进行排序,因为排序后已经保证了ai<ai+1,所以,我们只需要考虑树状数组中,右端比它小的就可以了。


#include
   
   
    
    

using namespace std;

const int maxn = 2 * 100000 + 5;
int n;
int val[maxn];
pair 
    
    
     
     
      
      , int> p[maxn];
vector 
      
      
       
        v;
int ind[maxn * 4];

void init(){
    scanf("%d", &n);
    for (int i = 0; i < n; i++){
        int l, r;
        scanf("%d %d", &l, &r);
        p[i] = make_pair(make_pair(l, r), i);
        v.push_back(l);
        v.push_back(r);
    }
}

void query(int x, int add){
    while (x <= v.size()){
        ind[x] += add;
        x += (x & -x);
    }
}

int sum(int x){
    int res = 0;
    while (x > 0){
        res += ind[x];
        x -= (x & -x);
    }
    return res;
}

void solve(){
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());
    for (int i = 0; i < n; i++){
        p[i].first.first = lower_bound(v.begin(), v.end(), p[i].first.first) - v.begin() + 1;
        p[i].first.second = lower_bound(v.begin(), v.end(), p[i].first.second) - v.begin() + 1;
        query(p[i].first.second, 1);
    }
    sort(p, p + n);
    /*for (int i = 0; i < n; i++){
        printf("p.second = %d\n", p[i].second);
        printf("%d %d\n", p[i].first.first, p[i].first.second);
    }*/
    for (int i = 0; i < n; i++){
        query(p[i].first.second, -1);
        val[p[i].second] = sum(p[i].first.second);
    }
    for (int i = 0; i < n; i++){
        printf("%d\n", val[i]);
    }
}

int main(){
    init();
    solve();
    return 0;
}
      
      
     
     
    
    
   
   




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值