4273: 玩具

6 篇文章 0 订阅
5 篇文章 0 订阅

http://oj.acm.zstu.edu.cn/JudgeOnline/problem.php?id=4273

4273: 玩具
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 851 Solved: 178
Description
商店有n个玩具,第i个玩具有价格a[i]和快乐值b[i]。有一天,小王来到商店想买一些玩具,商店老板告诉他,如果他买的所有玩具的位置是连续的,那么老板答应小王购买的所有玩具中某一个可以免费。小王接受老板的提议,他现在有零花钱k可以用来买玩具,那么他能获得的最大的快乐值是多少。
Input
第一行给测试总数T(T <= 100),接下来有T组测试数据。
每组测试数据第一行有两个数字n(1 <= n <= 5000)和k(0 <= k <= 1000000000)。
第二行有n个数字,第i个数字表示第i个玩具的价格a[i](1 <= a[i] <= 1000000)。
第三行有n个数字,第i个数字表示第i个玩具的快乐值b[i](1 <= b[i] <= 1000000)。
Output
每组测试输出小王能获得的最大快乐值。
Sample Input
3
5 14
1 2 3 4 5
5 4 3 2 1
3 1
100 1000 10000
100 1000 10000
1 0
1000000
1000000
Sample Output
15
10000
1000000

中文题意就不说了。
思路:连续、最大, 首先就可以想到尺取法:只要还能买, 就果断买买买!不能买就丢掉前面一个看下, 然后重复判断买买买。。。在这个过程中顺路判断下那个区间段最大。剩下只需确定区间最大值, 线段树不解释(下面的程序就是尺取法+线段树)。时间复杂度是O(nlogn)。
当然, 也可以枚举起点, 二分终点。因为单调性是显然的。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
#include <stack>
using namespace std;
typedef long long LL;
const int maxn=5e3+100;
LL n, k, cost[maxn], val[maxn];
LL mx;
int sum[maxn<<2];
void PushUP(int rt){
    sum[rt]=max(sum[rt<<1],sum[rt<<1|1]);
}
void updata(int p, int add, int l, int r, int rt)
{
    if (l==r){
        sum[rt]+=add;
        return ;
    }
    int m=(l+r)>>1;
    if (p<=m) updata(p, add, lson);
    else updata(p, add, rson);
    PushUP(rt);
}
int query(int L, int R, int l, int r, int rt)
{
    if (L<=l && r<=R){ return sum[rt];}
    int m=(l+r)>>1;
    int ret=0;
    if (L<=m) ret=max(ret,query(L, R, lson));
    if (R>m) ret=max(ret,query(L, R, rson));
    return ret;
}
//以上是线段树单点更新, 求区间最大值的代码
int main()
{
    int T;
    for (scanf("%d", &T); T; T--){
       cin>>n>>k;
       memset(sum, 0, sizeof sum);
       for (int i=0; i<n; i++){
            cin>>cost[i];
            updata(i, cost[i], 0, n-1, 1);//但点更新
       }
       for (int i=0; i<n; i++){
        cin>>val[i];
       }
       mx=0;
       LL hvc=0, mc=0, t=0, avl=0, s=0;
        for (;;){
            //试探下取第t个是否满足:
            while (t<n && hvc+cost[t]-(mc=query(s, t, 0, n-1, 1))<=k) {
                avl+=val[t];
                hvc+=cost[t];//满足更新
                if (avl>mx) mx=avl;//循环打擂
                t++;
            }
            if (t==n) {
                cout<<mx<<endl;
                break;
            }
            else{//取了太多, 放弃前面的,给后面留下机会
                hvc-=cost[s];
                avl-=val[s];
                s++;
            }
       }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值