hdu 2795 线段树

要注意:h和n的关系,创建树的时候,实际最多200000行

#include "stdio.h"
#include "stdlib.h"

#define MAX(a, b) ((a)>(b)?(a):(b))

typedef struct _Node{
	int max;
	int st, ed;
	struct _Node* lf;
	struct _Node* rt;
}Node, *pNode;

int h, w, n;
pNode root;

void create(pNode* r, int st, int ed){
	int m;
	pNode t;
	if(st>ed) return;
	t = (pNode)malloc(sizeof(Node));
	*r = t;
	t->max = w;
	t->st = st; t->ed = ed;
	if(st==ed){
		t->lf = t->rt = 0;
		return;
	}
	m = (st+ed)>>1;
	create(&(t->lf), st, m);
	create(&(t->rt), m+1, ed);
}

int search(pNode r, int ww){
	int t;
	if(ww>r->max) return -1;
	if(r->st == r->ed){
		r->max -= ww;
		return r->st;
	}
	t = search(r->lf, ww);
	if(t==-1)
		t = search(r->rt, ww);
	r->max = MAX(r->lf->max, r->rt->max);
	return t;
}

void del(pNode r){
	if(!r) return;
	del(r->lf);
	del(r->rt);
	free(r);
}

void main(){
	int i, t;
	freopen("in.txt", "r", stdin);
	while(scanf("%d %d %d", &h, &w, &n)!=EOF){
		create(&root, 1, h<n?h:n);  //这里要注意!!!
		for(i=0; i<n; i++){
			scanf("%d", &t);
			printf("%d\n", search(root, t));
		}
		del(root);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值