CodeForces - 652D -D. Nested Segments(树状数组+离散化)

本文介绍了一个算法问题:给定一系列不相交区间的线段,对于每个线段,计算其内部包含的其他线段数量。文章提供了一种利用离散化和线段树的数据结构解决方案,并通过具体输入输出示例展示了算法的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                                       Nested Segments

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

 

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1e6;
int n;
int sum[maxn],ans[maxn];

struct node{
	int x,y,id;
}r[maxn];

bool cmp(node a,node b){
	return a.y<b.y;
}

bool cmp1(node a,node b){
	if(a.x!=b.x) return a.x>b.x;
	return a.y < b.y;
}

int low_bit(int t){
	return t&(-t);
}

int queue(int t){
	int ans = 0;
	while(t>0){
		ans+=sum[t];
		t -= low_bit(t);
	}
	return ans;
}

void update(int t){
	while(t <= n){
		sum[t]++;
		t+=low_bit(t);
	}
}

int main(){
	scanf("%d",&n);
	for(int i = 1;i <= n;i++){
		scanf("%d%d",&r[i].x,&r[i].y);
		r[i].id = i;
	}
	sort(r+1,r+n+1,cmp);
	for(int i = 1;i <= n;i++){
		r[i].y = i; //离散化
	}
	sort(r+1,r+n+1,cmp1);
	for(int i = 1;i <= n;i++){
		ans[r[i].id] = queue(r[i].y);
		update(r[i].y);
	}
	for(int i = 1;i <= n;i++){
		printf("%d\n",ans[i]);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值