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
inputCopy
4
1 8
2 3
4 7
5 6
outputCopy
3
0
1
0
inputCopy
3
3 4
1 5
2 6
outputCopy
0
1
1
#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(false);cin.tie(0);
#define endl "\n"
const int N = 1e7 + 5;
using namespace std;
int ans[N], b[N], re[N], n, m, k;
int lowbit(int x){
return x & -x;
}
int update(int x, int m){
for(int i = x; i <= k; i += lowbit(i)){
ans[i] += m;
}
}
int query(int x){
int sum = 0;
for(int i = x; i > 0; i-= lowbit(i)){
sum += ans[i];
}
return sum;
}
int ls(int x){
x = lower_bound(b + 1, b + 1 + m, x) - b;
return x;
}
struct node{
int l, r, pos;
bool operator < (const node &x) const{//结构体内嵌比较函数
if(l == x.l)
return r > x.r;
return l < x.l;
}
}a[N];
int main(){
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++){
scanf("%d %d", &a[i].l, &a[i].r);
a[i].pos = i;
b[++k] = a[i].l;
b[++k] = a[i].r;
}
sort(a + 1, a + 1 + n);
sort(b + 1, b + 1 + k);
m = unique(b + 1, b + 1 + k) - (b + 1);
// ls() 离散, 求(左)右端点相对位置
for(int i = 1; i <= n; i++)
update(ls(a[i].r), 1);
for(int i = 1; i <= n; i++){
update(ls(a[i].r), -1);//delete
re[a[i].pos] = query(ls(a[i].r));
}
for(int i = 1; i <= n; i++)
printf("%d\n", re[i]);
}
离散模板:
for(int i = 1;i <= n; i++){
cin>>a[i];
b[i]=a[i];//创建两个数组
}
sort(b + 1, b + n + 1);//排序
int m = unique(b + 1, b + n + 1) - b - 1;//去重
for(int i = 1; i <= n; i++)
a[i]=lower_bound(b + 1, b + m + 1, a[i]) - b;//减去排序后数字对应的位置, 可求其相对大小