牛客小白月赛16 D、小阳买水果 (线段树或前缀和+后缀max)

题意
水果店里有 n n 个水果排成一列。店长要求顾客只能买一段连续的水果。
小阳对每个水果都有一个喜爱程度 a i a_i ,最终的满意度为他买到的水果的喜欢程度之和。
如果和为正(不管是正多少,只要大于 0即可),他就满意了。
小阳想知道在他满意的条件下最多能买多少个水果。
你能帮帮他吗?
思路:
维护一个前缀和,对于每个位置,找到在它后面且离他最远的大于它的值(前缀和)

O(n)做法

对于找到后面大于它且离他最远的位置,我们可以对求得的前缀和维护一个后缀max,然后每次尽可能往后移动。

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
const int man = 2e6+10;
#define IOS ios::sync_with_stdio(0)
#define endl '\n'
#define ll long long
const ll mod = 1e9+7;
ll pre[man];
ll maxx[man];

signed main() {
    #ifndef ONLINE_JUDGE
        //freopen("in.txt", "r", stdin);
        //freopen("out.txt","w",stdout);
    #endif
    int n;
    scanf("%d",&n);
    int ans = 0;
    for(int i =1 ;i <= n;++i){
        scanf("%lld",&pre[i]);
        pre[i] += pre[i-1];
    }
    memset(maxx,-0x3f,sizeof(maxx));
    for(int i = n;i >= 1;i--){
        maxx[i] = max(maxx[i+1],pre[i]);
    }
    for(int i = 0,j = 1;i < n;++i){
        if(pre[i]>=maxx[j])continue;
        while(j<=n&&pre[i]<maxx[j])++j;
        j--;
        ans = max(ans,j-i);
    }
    cout << ans <<endl;
    return 0;
}

O(nlogn)做法

线段树找后面大于它且离他最远的数。
维护一个区间maxx,如果右区间的maxx大于它,那么我么就往右边走,否则往左边。
找不到为-1.
具体看代码

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
const int man = 2e6+10;
#define IOS ios::sync_with_stdio(0)
#define endl '\n'
#define ll long long
const ll mod = 1e9+7;
ll pre[man];
 
ll maxx[man<<2];
 
void pushup(int rt){
    maxx[rt] = max(maxx[rt<<1],maxx[rt<<1|1]);
}
 
void build(int l,int r,int rt){
    maxx[rt] = -1;
    if(l==r){
        maxx[rt] = pre[l];
        return;
    }
    int m = l + r >>1;
    build(l,m,rt<<1);
    build(m+1,r,rt<<1|1);
    pushup(rt);
}
 
void query_max_id(int l,int r,int L,int R,int rt,int &ans,ll va){
    if(r<L||l>R)return;
    if(l==r){
        //cout << "maxx:" << maxx[rt] << " " << va <<endl;
        if(maxx[rt]>va)ans = l;
        else ans = -1;
        return;
    }
    int m = l + r >>1;
    if(maxx[rt<<1|1]>va)query_max_id(m+1,r,L,R,rt<<1|1,ans,va);
    else query_max_id(l,m,L,R,rt<<1,ans,va);
}
 
signed main() {
    #ifndef ONLINE_JUDGE
        //freopen("in.txt", "r", stdin);
        //freopen("out.txt","w",stdout);
    #endif
    int n;
    scanf("%d",&n);
    int ans = 0;
    for(int i =1 ;i <= n;++i){
        scanf("%lld",&pre[i]);
        if(pre[i]>0)ans = max(ans,1);
        pre[i] += pre[i-1];
        if(pre[i]>0)ans = max(ans,i);
    }
    if(ans==n)cout << ans << endl;
    else{
        build(1,n,1);
        for(int i = 1;i <= n;++i){
            int res = -1;
            query_max_id(1,n,i+1,n,1,res,pre[i]);
            if(res!=-1){
                ans = max(ans,res-i);
            }
        }
        cout << ans <<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43571920/article/details/107284323