一.题目链接
https://codeforces.com/contest/1440/problem/E
二.题意
n个商店,每个商店里面卖的东西的价值为a[i]. a数组非递增!!!
q组询问
1 x y : 从商店1到商店x,a[i]=max(a[i],x)
2 x y : 我有y元,从商店x到商店n走,每次能买就买,不能买就不买,问在几个商店买东西.
n,q<=2e5
三.算法分析
针对 1 x y
a数组原来是非递增的,做几次1操作以后还是非递增的.而且区间更新效果明显.
针对2 x y
用线段树,然后就先递归左子树,然后再递归右子树,很自然的可以做到从左往右走.
四.代码
#include<bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define sz(x) (int)x.size()
#define cl(x) x.clear()
#define all(x) x.begin() , x.end()
#define rep(i , x , n) for(int i = x ; i <= n ; i ++)
#define per(i , n , x) for(int i = n ; i >= x ; i --)
#define mem0(x) memset(x , 0 , sizeof(x))
#define mem_1(x) memset(x , -1 , sizeof(x))
#define mem_inf(x) memset(x , 0x3f , sizeof(x))
#define debug(x) cerr << #x << " = " << x << '\n'
#define ddebug(x , y) cerr << #x << " = " << x << " " << #y << " = " << y << '\n'
#define tr t[root]
#define lson t[root << 1]
#define rson t[root << 1 | 1]
using namespace std ;
typedef long long ll ;
typedef long double ld ;
typedef pair<int , int> pii ;
typedef pair<ll , ll> pll ;
typedef double db ;
const int inf = 0x3f3f3f3f ;
const double eps = 1e-6 ;
/*-------------------------------end-----------------------------------------*/
const int maxn=2e5+1000;
int a[maxn],n,q;
struct segtree{
int l,r;
ll maxx,minn,tag,val;
}t[maxn<<2];
void pushup(int root) {
tr.maxx=max(lson.maxx,rson.maxx);
tr.minn=min(lson.minn,rson.minn);
tr.val=lson.val+rson.val;
return;
}
void build(int root,int l,int r) {
tr.tag=0,tr.l=l,tr.r=r;
if (l==r) {
tr.maxx=tr.minn=tr.val=a[l];
return;
}
int mid=(l+r)>>1;
build(root<<1,l,mid);
build(root<<1|1,mid+1,r);
pushup(root);
}
void spread(int root) {
if (tr.tag) {
lson.maxx=lson.minn=lson.tag=tr.tag;
lson.val=(ll)tr.tag*(lson.r-lson.l+1);
rson.maxx=rson.minn=rson.tag=tr.tag;
rson.val=(ll)tr.tag*(rson.r-rson.l+1);
tr.tag=0;
}
return;
}
void update(int root,int l,int r,int x) {
if (tr.minn>=x) return;
if (tr.l>=l && tr.r<=r && tr.maxx<=x) {
tr.maxx=tr.minn=tr.tag=x;
tr.val=(ll)x*(tr.r-tr.l+1);
return ;
}
spread(root);
int mid=(tr.l+tr.r)>>1;
if (l<=mid) update(root<<1,l,r,x);
if (r>mid) update(root<<1|1,l,r,x);
pushup(root);
}
int query(int root,int l,int r,int & x) {
if (tr.minn>x) return 0;
if (tr.l>=l && tr.r<=r && tr.val<=x) {
x-=tr.val;
return tr.r-tr.l+1;
}
spread(root);
int mid=(tr.l+tr.r)>>1,ans=0;
if (l<=mid) ans+=query(root<<1,l,r,x);
if (r>mid) ans+=query(root<<1|1,l,r,x);
return ans;
}
int main() {
cin>>n>>q;
rep(i,1,n) scanf("%d",&a[i]);
build(1,1,n);
while (q--) {
int op,x,y;
scanf("%d%d%d",&op,&x,&y);
if (op==1) update(1,1,x,y);
else printf("%d\n",query(1,x,n,y));
}
return 0;
}
五.总结
- 线段树的t[]数组是4*n,刚开始一直re.
- 懒标记多手画,容易写错.