hdu 2795 线段树

时间:2022-07-20 11:45:25

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2795

 #include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector> #define maxn 222222
#define lson l,mid,u<<1
#define rson mid+1,r,u<<1|1
using namespace std; const int INF = 0x3f3f3f;
int h,w,n;
int seg[maxn<<];
int row; int Push_UP(int u){
seg[u] = max(seg[u<<],seg[u<<|]); //****这个地方 u<<1|1 不能换为 u << 1 +1
}
void build(int l,int r,int u){
if(l == r){
seg[u] = w;
return;
}
int mid = (l + r)>>;
build(lson);
build(rson);
Push_UP(u);
}
void Update(int loc,int num,int l,int r,int u){
if(l == r){ // 这个地方要注意!!
seg[u] -= num;
return;
}
int mid = (l + r)/;
if(loc <= mid) Update(loc,num,lson);
else Update(loc,num,rson);
Push_UP(u);
} int Query(int num,int l,int r,int u){
if(seg[u] < num) return -; if(l == r && seg[u] >= num){
return l;
}
int ret = ;
int mid = (l + r)/;
ret = Query(num,lson);
if(ret != -) return ret;
else return Query(num,rson);
}
int main()
{
//if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);}
while(cin>>h>>w>>n){
if(h > n) h = n;
build(,h,);
while(n--){
int a;
scanf("%d\n",&a);
row = Query(a,,h,);
if(row == -) printf("-1\n");
else{
Update(row,a,,h,);
printf("%d\n",row);
}
}
}
}

参考别人的改进版:

 #include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <queue>
#include <vector> #define maxn 222222
#define lson l,mid,u<<1
#define rson mid+1,r,u<<1|1
using namespace std; const int INF = 0x3f3f3f;
int h,w,n;
int seg[maxn<<]; int Push_UP(int u){
seg[u] = max(seg[u<<],seg[u<<|]); //****这个地方 u<<1|1 不能换为 u << 1 +1
}
void build(int l,int r,int u){
if(l == r){
seg[u] = w;
return;
}
int mid = (l + r)>>;
build(lson);
build(rson);
Push_UP(u);
}
int Query(int num,int l,int r,int u){
if(l == r ){
seg[u] -= num;
return l;
}
int ret = ;
int mid = (l + r)/;
if(seg[u<<] >= num) ret = Query(num,lson);
else ret = Query(num,rson);
Push_UP(u);
return ret;
}
int main()
{
//if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);}
while(cin>>h>>w>>n){
if(h > n) h = n;
build(,h,);
while(n--){
int num;
scanf("%d\n",&num);
if(seg[]<num) printf("-1\n");
else printf("%d\n",Query(num,,h,));
}
}
}