hdu 2795 线段树
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2795
1 #include <cstdio> 2 #include <cmath> 3 #include <algorithm> 4 #include <iostream> 5 #include <cstring> 6 #include <queue> 7 #include <vector> 8 9 #define maxn 222222 10 #define lson l,mid,u<<1 11 #define rson mid+1,r,u<<1|1 12 using namespace std; 13 14 const int INF = 0x3f3f3f; 15 int h,w,n; 16 int seg[maxn<<2]; 17 int row; 18 19 int Push_UP(int u){ 20 seg[u] = max(seg[u<<1],seg[u<<1|1]); //****这个地方 u<<1|1 不能换为 u << 1 +1 21 } 22 void build(int l,int r,int u){ 23 if(l == r){ 24 seg[u] = w; 25 return; 26 } 27 int mid = (l + r)>>1; 28 build(lson); 29 build(rson); 30 Push_UP(u); 31 } 32 void Update(int loc,int num,int l,int r,int u){ 33 if(l == r){ // 这个地方要注意!! 34 seg[u] -= num; 35 return; 36 } 37 int mid = (l + r)/2; 38 if(loc <= mid) Update(loc,num,lson); 39 else Update(loc,num,rson); 40 Push_UP(u); 41 } 42 43 int Query(int num,int l,int r,int u){ 44 if(seg[u] < num) return -1; 45 46 if(l == r && seg[u] >= num){ 47 return l; 48 } 49 int ret = 0; 50 int mid = (l + r)/2; 51 ret = Query(num,lson); 52 if(ret != -1) return ret; 53 else return Query(num,rson); 54 } 55 int main() 56 { 57 //if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);} 58 while(cin>>h>>w>>n){ 59 if(h > n) h = n; 60 build(1,h,1); 61 while(n--){ 62 int a; 63 scanf("%d\n",&a); 64 row = Query(a,1,h,1); 65 if(row == -1) printf("-1\n"); 66 else{ 67 Update(row,a,1,h,1); 68 printf("%d\n",row); 69 } 70 } 71 } 72 }
参考别人的改进版:
1 #include <cstdio> 2 #include <cmath> 3 #include <algorithm> 4 #include <iostream> 5 #include <cstring> 6 #include <queue> 7 #include <vector> 8 9 #define maxn 222222 10 #define lson l,mid,u<<1 11 #define rson mid+1,r,u<<1|1 12 using namespace std; 13 14 const int INF = 0x3f3f3f; 15 int h,w,n; 16 int seg[maxn<<2]; 17 18 19 int Push_UP(int u){ 20 seg[u] = max(seg[u<<1],seg[u<<1|1]); //****这个地方 u<<1|1 不能换为 u << 1 +1 21 } 22 void build(int l,int r,int u){ 23 if(l == r){ 24 seg[u] = w; 25 return; 26 } 27 int mid = (l + r)>>1; 28 build(lson); 29 build(rson); 30 Push_UP(u); 31 } 32 int Query(int num,int l,int r,int u){ 33 if(l == r ){ 34 seg[u] -= num; 35 return l; 36 } 37 int ret = 0; 38 int mid = (l + r)/2; 39 if(seg[u<<1] >= num) ret = Query(num,lson); 40 else ret = Query(num,rson); 41 Push_UP(u); 42 return ret; 43 } 44 int main() 45 { 46 //if(freopen("input.txt","r",stdin)== NULL) {printf("Error\n"); exit(0);} 47 while(cin>>h>>w>>n){ 48 if(h > n) h = n; 49 build(1,h,1); 50 while(n--){ 51 int num; 52 scanf("%d\n",&num); 53 if(seg[1]<num) printf("-1\n"); 54 else printf("%d\n",Query(num,1,h,1)); 55 } 56 } 57 }