POJ_2481(树状数组)

本文探讨了如何高效处理区间更新和查询的问题,通过使用线段树和离散化技术,实现快速的区间操作和查询优化。重点在于解决两个区间完全相同情况下的优化策略。

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

本题的关键在于要考虑到两个区间完全相同的情况,其他的不用考虑太多。


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;

const int maxn = 100000 + 300;
int c[maxn];
int ans[maxn];
struct cow{
	int s;
	int e;
	int in;
	bool operator < (const cow& z) const{
		if(z.s == s) return z.e < e;
		else return z.s > s;
	}
}co[maxn], pri;

int lowbit(int x){
	return x & (-x);
}
int sum(int x){
	int t = 0;
	while(x > 0){
		t += c[x];
		x -= lowbit(x);		
	}
	return t;
} 
int update(int x){
	while(x < maxn){
		c[x]++;
		x += lowbit(x);
	}
	return 0;
}

int main(){
	int tot;
	while(scanf("%d", &tot) && tot){
		memset(c, 0, sizeof(c));
		memset(co, 0, sizeof(co));
		memset(ans, 0, sizeof(ans));
		for(int i = 0; i < tot; ++i){
			scanf("%d%d", &co[i].s, &co[i].e);
			co[i].s++; co[i].e++;
			co[i].in = i;
		}
		sort(co, co+tot);
		pri.s = co[0].s; pri.e = co[0].e; pri.in = co[0].in;
		co[0].e++;
		ans[co[0].in] = 0 - sum(co[0].e);
		update(co[0].e);
		for(int i = 1; i < tot; ++i){ 
			int s = co[i].e;
			s++;
			if(pri.e == co[i].e && pri.s == co[i].s){
				ans[co[i].in] = ans[co[i-1].in];
			}else{
				ans[co[i].in] = i - sum(s-1);
			}
			pri.e = co[i].e; pri.s = co[i].s; pri.in = co[i].in;
			update(s);
		}
		int i;
		for(i = 0; i < tot - 1; ++i){
			printf("%d ", ans[i]);
		} 
		printf("%d\n", ans[i]);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值