CodeForces D. Nested Segments【逆序对类型】

本文介绍了一种解决区间嵌套问题的有效算法,通过离散化处理和利用树状数组来统计每个区间被包含的次数。输入为一系列不重合区间的端点坐标,输出每个区间内所含有的其他区间数量。

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

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



AC代码:

//离散化之后 将结束时间看成id 按开始时间降序插入统计插入元素之前已插入的元素个数即为该元素的贡献 

#include<cstdio>
#include<algorithm>

using namespace std;

const int MAXN=2e5+11;

struct Node{
	int l,r,id;
}b[MAXN<<1];
int C[MAXN<<1],a[MAXN<<1],ans[MAXN];

int Lowbit(int x) {
	return x&(-x);
} 
void Add(int x,int d,int N) {
	while(x<=N) {
		C[x]+=d; x+=Lowbit(x);
	}
}
int Sum(int x) {
	int ret=0;
	while(x>0) {
		ret+=C[x]; x-=Lowbit(x); 
	}
	return ret;
}

bool cmp(Node a,Node b) {
	if(a.l!=b.l) return a.l>b.l;
	return a.r<b.r;
}

int main() {
	int N;
	while(~scanf("%d",&N)) {
		int cnt=0;
		for(int i=0;i<N;++i) {
			scanf("%d%d",&b[i].l,&b[i].r);
			a[cnt++]=b[i].l; a[cnt++]=b[i].r; 
			b[i].id=i;
		}
		sort(a,a+cnt);
		int top=unique(a,a+cnt)-a;
		for(int i=0;i<N;++i) {
			int p=lower_bound(a,a+top,b[i].l)-a;
			b[i].l=p+1;
			p=lower_bound(a,a+top,b[i].r)-a;
			b[i].r=p+1;
		}
		top++;
		for(int i=0;i<=top;++i) C[i]=0;
		sort(b,b+N,cmp);
		for(int i=0;i<N;++i) {
			Add(b[i].r,1,top); 
			ans[b[i].id]=Sum(b[i].r-1); 
		}
		for(int i=0;i<N;++i) printf("%d\n",ans[i]);
	} 
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值