1 Star 0 Fork 1

saigon/Algorithms

forked from charlieshu/Algorithms 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
P3372 【模板】线段树 1.cpp 1.84 KB
一键复制 编辑 原始数据 按行查看 历史
charlie 提交于 2024-01-09 00:01 . move from github to gitee
#include <iostream>
#include <math.h>
#define int long long
using namespace std;
struct node{
int l=-1,r;
int sum=0,add=0;
};
int build(int l,int r,int index,node *tree,int *a){
int mid=(l+r)/2;
tree[index].l = l;
tree[index].r = r;
if(l == r){
tree[index].sum = a[l];
return tree[index].sum;
}
tree[index].sum = build(l,mid,(index+1)*2-1,tree,a)+build(mid+1,r,(index+1)*2,tree,a);
return tree[index].sum;
}
int sum(int l,int r,int index,node *tree){
if(tree[index].l >= l && tree[index].r <= r)
return tree[index].sum+tree[index].add*(tree[index].r-tree[index].l+1);
if(tree[index].l > r || tree[index].r < l)
return 0;
tree[(index+1)*2-1].add += tree[index].add;
tree[(index+1)*2].add += tree[index].add;
tree[index].sum += tree[index].add*(tree[index].r-tree[index].l+1);
tree[index].add = 0;
return sum(l,r,(index+1)*2-1,tree)+sum(l,r,(index+1)*2,tree);
}
void add(int l,int r,int k,int index,node *tree){
if(tree[index].l >= l && tree[index].r <= r){
tree[index].add += k;
return;
}
if(tree[index].l > r || tree[index].r < l)
return;
tree[index].sum += k*(min(r,tree[index].r)-max(l,tree[index].l)+1);
add(l,r,k,(index+1)*2-1,tree);
add(l,r,k,(index+1)*2,tree);
return;
}
signed main(){
int n,m;
cin>>n>>m;
int nn=n;
int nsum=1;
while(nn > 0){
nn /= 2;
nsum *= 2;
}
if(nsum > n){
nsum *= 2;
}
nsum -= 1;
int a[n];
node tree[nsum];
for(int i=0;i<n;i++)
cin>>a[i];
build(0,n-1,0,tree,a);
for(int i=0;i<m;i++){
int t;
cin>>t;
if(t == 1){
int x,y,k;
cin>>x>>y>>k;
add(x-1,y-1,k,0,tree);
}
else{
int x,y;
cin>>x>>y;
cout<<sum(x-1,y-1,0,tree)<<endl;
}
}
// for(int i=0;i<nsum;i++)
// cout<<"["<<i<<"] "<<tree[i].l<<" "<<tree[i].r<<" "<<tree[i].add<<" "<<tree[i].sum<<endl;
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/saigonshu/algorithm.git
git@gitee.com:saigonshu/algorithm.git
saigonshu
algorithm
Algorithms
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385