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.
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.
Print n lines. The j-th of them should contain the only integer aj — the number of segments contained in the j-th segment.
4 1 8 2 3 4 7 5 6
3 0 1 0
3 3 4 1 5 2 6
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;
}