HDU - 2795 -- Billboard (树状数组做法)

题目来源: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;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值