题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2795
线段树做法:https://blog.csdn.net/moon_sky1999/article/details/81274186
刚开始做这道题的时候,思路大概是二分+线段树维护区间最大值,二分区间[1,r]的右端点r,查询其最大值验证是否满足题意,直到得到最小的r,将a[r]取走。O( n * (log n) ^ 2 )的复杂度,然后就,愉快地TLE掉了。
几次尝试之后,我想到了常数比线段树小的树状数组。然后将线段树改成了树状数组,竟、然、过、了!
下图为两种方法的结果对比(上方为线段树做法,复杂度较低)。
代码——复杂度为 O( n * (log n) ^ 2 ) :
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
const int maxn=2e6+10;
int h,w,n,m;
int c[maxn],a[maxn];
inline int lb(int x) {
return x & -x;
}
int query(int x) {
int tot = 0;
for (; x; x -= lb(x))
tot = max(tot, c[x]);
return tot;
}
void update(int x) {
for (; x <= n; x += lb(x)) {
c[x] = a[x];
int t = x - lb(x);
for (int y = x - 1; y && y - lb(y) >= t; y -= lb(y))
c[x] = max(c[x], c[y]);
}
}
int main() {
while (~scanf("%d%d%d", &h, &w, &m)) {
n = min(m, h);
for (int i = 1; i <= n; ++i) {
c[i] = w;
a[i] = w;
}
int x;
for (int i = 1; i <= m; ++i) {
scanf("%d", &x);
int l = 1, r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (query(mid) >= x)r = mid;
else l = mid + 1;
}
if (a[l] < x)
printf("-1\n");
else {
a[l] -= x;
update(l);
printf("%d\n", l);
}
}
}
return 0;
}