二叉搜索树

题目:CF1439C Greedy Shopping

题目链接:https://www.luogu.com.cn/problem/CF1439C?contestId=38677

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll t[1020000],sum[1020000],mn[1020000],tag[1020000];
ll n,m,a[1020000];
ll opt,x,y;

void build(ll p,ll l ,ll r)
{
    if(l==r)
    {
        t[p]=sum[p]=mn[p]=a[l];
        return;
    }
    
    ll mid=(l+r)>>1;
    
    build(p<<1,l,mid);
    build(p<<1|1,mid+1,r);
    
    sum[p]=sum[p<<1]+sum[p<<1|1];
    mn[p]=min(mn[p<<1],mn[p<<1|1]);
}

void pushdown(ll p,ll l,ll r)
{
    if(tag[p])
    {
        ll mid=(l+r)>>1;
        tag[p<<1]=tag[p<<1|1]=tag[p];
        mn[p<<1]=mn[p<<1|1]=tag[p];
        sum[p<<1]=1ll*(mid-l+1)*tag[p];
        sum[p<<1|1]=1ll*(r-mid)*tag[p];
        tag[p]=0;
    }
    
}

ll find(ll p,ll l,ll r,ll y)
{
    if(l==r)
    {
        if(y>sum[p]) 
        return l;
        return l+1;
    } 
    
    ll mid=(l+r)>>1;
    pushdown(p,l,r);
    
    if(mn[p<<1]>=y) return find(p<<1|1,mid+1,r,y);
    return find(p<<1,l,mid,y); 
}

void chang(ll p,ll l,ll r,ll ql,ll qr,ll y)
{
    if(ql<=l&&qr>=r) 
    {
        tag[p]=y;
        mn[p]=y;
        sum[p]=(r-l+1)*y;
        return;
    }
    
    ll mid=(l+r)>>1;
    pushdown(p,l,r);
    
    if(ql<=mid) chang(p<<1,l,mid,ql,qr,y);
    if(qr>mid) chang(p<<1|1,mid+1,r,ql,qr,y);
    
    sum[p]=sum[p<<1]+sum[p<<1|1];
    mn[p]=min(mn[p<<1],mn[p<<1|1]);
}

ll ans(ll p,ll l,ll r,ll ql,ll &y)
{
    if(r<ql||y<mn[p]) return 0;
    if(l>=ql&&y>=sum[p])
    {
        y-=sum[p];
        return min(n,r)-l+1;
    }
    pushdown(p,l,r);
    ll mid=(l+r)>>1;
    ll num=0;
    if(ql<=mid) num+=ans(p<<1,l,mid,ql,y);
    num+=ans(p<<1|1,mid+1,r,ql,y);
    return num;
    
}


int main()
{
    cin>>n>>m;
    for(ll i=1;i<=n;i++) cin>>a[i];
    
    build(1,1,n);
    
    while(m--)
    {
        cin>>opt>>x>>y;
        
        if(opt==1)
        {
            ll l=find(1,1,n,y);
//            cout<<l<<" lll
";
            if(x>=l) chang(1,1,n,l,x,y);  
        }
        
        else
        {
            cout<<ans(1,1,n,x,y)<<'
';
        }
    }
    
    return 0;
}
原文地址:https://www.cnblogs.com/yxr001002/p/14134324.html