第一题:做过,不解释(直接上二分)
第二题:一道裸的线段树题目
1462 序列更新
题目描述 对于一个长度为n的A序列,有两次操作:
(1)0 L R x b,表示对于i∈[L,R],A[i]加上x-(i-L)*b
(2)1 L R 输出sum(A[L…R])
输入 第一行两个数n和m,表示序列长度和操作数。
第二行n个数,表示序列中的元素。
接下来m行,每行如题目描述的两种形式。
输出 对于(2)操作输出对应的值m,结果对1e9+7取余。
这题有两个注意点:
一.可以把x-(i-L)*b 拆成x+L*b 与i*b 然后传入两个参数,延迟更新
二.取模需要特别注意,千万不要在除法前取模
贴上一段AC代码
#include<bits/stdc++.h>
using namespace std;
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
#define ll long long
#define N 100005
const int M=1e9+7;
ll A[N];
struct node {
int l,r;
long long add,x;
long long sum;
} tree[N<<2];
void up(int p) {
tree[p].sum=tree[p<<1].sum+tree[p<<1|1].sum;
tree[p].sum%=M;
}
void down(int p) {
if(tree[p].add==0&&tree[p].x==0)return;
tree[p<<1].add+=tree[p].add;
tree[p<<1|1].add+=tree[p].add;
tree[p<<1].x+=tree[p].x;
tree[p<<1|1].x+=tree[p].x;
tree[p<<1].sum+=1LL*(tree[p<<1].r-tree[p<<1].l+1)%M*tree[p].add-1LL*(tree[p<<1].l+tree[p<<1].r)%M*(tree[p<<1].r-tree[p<<1].l+1)/2*tree[p].x;
tree[p<<1|1].sum+=1LL*(tree[p<<1|1].r-tree[p<<1|1].l+1)%M*tree[p].add-1LL*(tree[p<<1|1].l+tree[p<<1|1].r)%M*(tree[p<<1|1].r-tree[p<<1|1].l+1)/2*tree[p].x;
tree[p<<1].sum%=M;
tree[p<<1].sum%=M;
tree[p].add=0;
tree[p].x=0;
}
void build(int l,int r,int p) {
tree[p].l=l,tree[p].r=r,tree[p].add=0,tree[p].x=0;
if(l==r) {
tree[p].sum=A[l];
return;
}
int mid=(l+r)>>1;
build(l,mid,p<<1);
build(mid+1,r,p<<1|1);
up(p);
}
ll query(int l,int r,int p) {
if(tree[p].l==l&&tree[p].r==r) {
return tree[p].sum%M;
}
down(p);
int mid=(tree[p].l+tree[p].r)>>1;
if(r<=mid)return query(l,r,p<<1);
else if(l>mid)return query(l,r,p<<1|1);
else return 1LL*((query(l,mid,p<<1)+query(mid+1,r,p<<1|1)))%M;
}
void update(int l,int r,int x,int y,int p) {
if(tree[p].l==l&&tree[p].r==r) {
tree[p].sum+=1LL*(tree[p].r-tree[p].l+1)*x%M-1LL*(tree[p].r+tree[p].l)%M*(tree[p].r-tree[p].l+1)%M*y/2;
tree[p].sum%=M;
tree[p].add+=x;
tree[p].x+=y;
return;
}
down(p);
int mid=(tree[p].l+tree[p].r)>>1;
if(r<=mid)update(l,r,x,y,p<<1);
else if(l>mid)update(l,r,x,y,p<<1|1);
else update(l,mid,x,y,p<<1),update(mid+1,r,x,y,p<<1|1);
up(p);
}
int main() {
int n,m;
cin>>n>>m;
FOR(i,1,n)scanf("%lld",&A[i]);
build(1,n,1);
FOR(i,1,m) {
int b;
scanf("%d",&b);
if(b) {
int x,y;
scanf("%d%d",&x,&y);
printf("%lld\n",(query(x,y,1)+M)%M);
} else {
int l,r,x,b;
scanf("%d%d%d%d",&l,&r,&x,&b);
update(l,r,x+b*l,b,1);
}
}
return 0;
}
第三题测试数据弱,暴力可以过,当然也可以线段树,堆优化
最强的还是单调栈优化,复杂度O(n)