POJ 2481 Cows

本文探讨了树状数组的应用于解决区间更新问题,并详细介绍了相关数据结构、算法实现及示例代码。

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

It's a tree_array problem.

The portal:http://poj.org/problem?id=2481

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>

using namespace std;

const int N = 1e5+5;
const int M = 1e5+5;

int Bit[M << 1];

struct Node {
	int x,y,r,value;
}a[N];

void Insert(int x,int value) {
	for(int i = x; i <= M; i += i & (-i)){
		Bit[i] += value;
	}
}

int Query(int x){
	int ret = 0;
	if(x <= 0)return 0;
	for(int i = x;i;i -= i & (-i)){
		ret += Bit[i];
	}
	return ret;
}

int cmp1(const void * a1,const void * a2){
	struct Node p1 = *(struct Node *)a1;
	struct Node p2 = *(struct Node *)a2;
	if(p1.y == p2.y) return p1.x - p2.x;
	return p2.y - p1.y;
}

int cmp2(const void * a1,const void * a2){
	struct Node p1 = *(struct Node *)a1;
	struct Node p2 = *(struct Node *)a2;
	return p1.r - p2.r;
}

void Deal_with(){
	int n;
	while(scanf("%d",&n),n){
		memset(a,0,sizeof(a));
		memset(Bit,0,sizeof(Bit));
		for(int i=0;i<n;i++){
			scanf("%d %d",&a[i].x,&a[i].y);
			a[i].x ++ ; a[i].y ++;
			//Because a[i].x may equal '0';
			a[i].r = i;
		}
		qsort(a,n,sizeof(struct Node),cmp1);
		//Use y to first condition.(From higher to lower);Use x to second condition.(From lower to higher.) 
		Insert(a[0].x,1);
		for(int i=1;i<n;i++){
			if(a[i].x == a[i-1].x && a[i].y == a[i-1].y){
				a[i].value = a[i-1].value;
				Insert(a[i].x,1);
				//Add the line is important; 
				continue;
			}
			a[i].value = Query(a[i].x);
			Insert(a[i].x,1);
		}
		qsort(a,n,sizeof(struct Node),cmp2);
		//Use a[i].r to recmp the array a;
		for(int i=0;i<n;i++){
			printf("%d",a[i].value);
			printf(i == n - 1 ? "\n" : " ");
			// if (i == n - 1) printf("\n"); else printf(" ");
		}
	}
}

int main(void){
	//freopen("a.in","r",stdin);
	Deal_with();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值