要注意: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);
}
}