Fenwick tree (CF Educational Codeforces Round 10)

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


利用map容器把线段端点范围重新调整,然后,对线段左端点从大到小排序,利用树状数组查找每段线段包括的线段数目。


#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;++i)
#define per(i,a,n) for(int i=n-1;i>=a;--i)
#define mem(a,t) memset(a,t,sizeof(a))
#define pb push_back
#define mp make_pair
#define sz(a) (int)a.size()
#define fi first
#define se second
typedef long long LL;
#define N 400005
const int M=10005;
vector<pair<pair<int,int>,int> >a,b;
vector<int>c;
map<int,int>p;
int ans[N];
int f[N];
int n;
void recal() // 把线段端点值重新调整
{
    sort(c.begin(),c.end());
    int len=1,l,r;
    rep(i,0,n*2){
        p[c[i]]=len++;
    }
    rep(i,0,n){
        l=p[a[i].fi.fi];
        r=p[a[i].fi.se];
        b.pb(mp(mp(l,r),a[i].se));
    }
}
bool cmp1(pair<pair<int,int>,int>a,pair<pair<int,int>,int>b)
{                               //对线段左端点从大到小排序
    return a.fi.fi>b.fi.fi;
}

int lowbit(int x) //得到二进制X最低位1的值,(利用补码原理)
{                  //补码为原码加一,
    return x&(-x); //x =1: 1 &-1(设位数为8)0000 0001 & 1111 1111 = 1
}
int query(int x)
{
    int s=0;
    for(int i=x;i>0;i-=lowbit(i)){
        s+=f[i];
    }
    return s;
}
void update(int x,int t)  
{
    for(int i=x;i<=2*n;i+=lowbit(i)){
        f[i]+=t;
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    int l,r;
    scanf("%d",&n);
    rep(i,0,n){
        scanf("%d%d",&l,&r);
        a.pb(mp(mp(l,r),i));
        c.pb(l);
        c.pb(r);
    }
    recal();
    sort(b.begin(),b.end(),cmp1);
    int t,x;
    rep(i,0,n)
    {
        x=b[i].fi.se;
        t=query(x);
        ans[b[i].se]=t;
        update(x,1);
    }
    rep(i,0,n) printf("%d\n",ans[i]);
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值