当前位置: 代码迷 >> 综合 >> luogu 1438无聊的数列 线段树区间修改区间求和
  详细解决方案

luogu 1438无聊的数列 线段树区间修改区间求和

热度:71   发布时间:2023-11-24 00:36:23.0

题意,n(1e5)个数,m(1e5)个操作,第一种将[L,R]范围内的数分别加上首项为K,公差为D的等差数列,第二种询问[L,R]范围内区间和

维护差分数组,每次修改时,sun[l]+=k;(l,R]:sum[i]+=D;sum[R+1]-=(K+(R-L)*D);

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e5+5;
int n,m;
struct node
{int l,r,sum,lazy;
}tree[maxn<<2];
int s[maxn];void build(int root, int l, int r) {tree[root].l = l, tree[root].r = r;tree[root].lazy = 0; if(l == r)return;int mid = (l + r) >> 1; build(root<<1, l, mid);build(root<<1|1, mid+1, r);
}
void push_up(int root) 
{tree[root].sum = tree[root<<1].sum + tree[root<<1|1].sum;
}
void push_down(int root) 
{tree[root<<1].lazy += tree[root].lazy;tree[root<<1|1].lazy += tree[root].lazy;tree[root<<1].sum += (tree[root<<1].r - tree[root<<1].l + 1) * tree[root].lazy;tree[root<<1|1].sum += (tree[root<<1|1].r - tree[root<<1|1].l + 1) * tree[root].lazy;tree[root].lazy = 0;
}
void update(int root,int l, int r, int val)
{// cout << root << " "<< tree[root].l <<" " << tree[root].r << endl;if(tree[root].l >=l && tree[root].r <= r){ tree[root].lazy += val, tree[root].sum += (tree[root].r - tree[root].l + 1) * val;return;}push_down(root);int mid = (tree[root].r + tree[root].l) >> 1;if(mid >= l)update(root<<1, l, r, val);if(mid < r) update(root<<1|1, l, r, val);push_up(root);
}
int query(int root,int l, int r) 
{if(tree[root].l >= l && tree[root].r <= r) return tree[root].sum;push_down(root);int mid = (tree[root].l + tree[root].r) >> 1;int res = 0;if(mid >= l)res+=query(root<<1, l, r);if(mid < r)res+=query(root<<1|1, l, r);return res;	
}
int main()
{cin>>n>>m;for(int i=1;i<=n;i++)cin>>s[i];build(1, 1, n);// for(int i=1;i<=n<<2;i++)cout<<i << " " << tree[i].l <<" "<<tree[i].r << endl;int type,L,R,K,D,ask;while(m--){cin>>type;if(type == 1) {cin>>L>>R>>K>>D;update(1,L,L,K);if(R>L)update(1,L+1,R,D);int N = R - L + 1;if(R != n) update(1,R+1,R+1, -(K+(N-1)*D));	}else {cin>>ask;printf("%d\n",s[ask]+query(1,1,ask));}}
}