1. 程式人生 > >【洛谷P3372】【模板】線段樹 1

【洛谷P3372】【模板】線段樹 1

return blog 限制 空格 ges 進行 esp -m node

題目描述

如題,已知一個數列,你需要進行下面兩種操作:

1.將某區間每一個數加上x

2.求出某區間每一個數的和

輸入輸出格式

輸入格式:

第一行包含兩個整數N、M,分別表示該數列數字的個數和操作的總個數。

第二行包含N個用空格分隔的整數,其中第i個數字表示數列第i項的初始值。

接下來M行每行包含3或4個整數,表示一個操作,具體如下:

操作1: 格式:1 x y k 含義:將區間[x,y]內每個數加上k

操作2: 格式:2 x y 含義:輸出區間[x,y]內每個數的和

輸出格式:

輸出包含若幹行整數,即為所有操作2的結果。

輸入輸出樣例

輸入樣例#1:
5 5
1 5 4 2 3
2 2 4
1 2 3 2
2 3 4
1 1 5 1
2 1 4
輸出樣例#1:
11
8
20

說明

時空限制:1000ms,128M

數據規模:

對於30%的數據:N<=8,M<=10

對於70%的數據:N<=1000,M<=10000

對於100%的數據:N<=100000,M<=100000

(數據已經過加強^_^,保證在int64/long long數據範圍內)

樣例說明:

技術分享

分析

此題同codevs1082線段樹練習3。

代碼

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=200000+5; typedef long long ll; inline int read() { int x=0,f=1; char ch=getchar(); while(ch<0||ch>9){if(ch==-)f=-1; ch=getchar();} while(ch>=0&&ch<=9){x=x*10+ch-0; ch=getchar();} return x*f; } int n,m,len; int a[maxn]; struct node { int l,r,lc,rc,add; ll c; }tr[maxn
<<1]; inline void bt(int x,int y) { len++; int now=len; tr[now].l=x; tr[now].r=y; if(x==y) tr[now].c=a[x]; else { int mid=(x+y)>>1; tr[now].lc=len+1; bt(x,mid); tr[now].rc=len+1; bt(mid+1,y); tr[now].c=tr[tr[now].lc].c+tr[tr[now].rc].c; } } inline void pushdown(int now) { int lc=tr[now].lc,rc=tr[now].rc; tr[lc].c+=tr[now].add*(tr[lc].r-tr[lc].l+1); tr[rc].c+=tr[now].add*(tr[rc].r-tr[rc].l+1); tr[lc].add+=tr[now].add; tr[rc].add+=tr[now].add; tr[now].add=0; } inline void update(int now,int x,int y,int k) { if(tr[now].l==x&&tr[now].r==y) { tr[now].c+=k*(tr[now].r-tr[now].l+1); tr[now].add+=k; }else { int lc=tr[now].lc,rc=tr[now].rc; pushdown(now); int mid=(tr[now].l+tr[now].r)>>1; if(y<=mid) update(lc,x,y,k); else if(x>=mid+1) update(rc,x,y,k); else {update(lc,x,mid,k); update(rc,mid+1,y,k);} tr[now].c=tr[lc].c+tr[rc].c; } } inline ll query(int now,int x,int y) { if(tr[now].l==x&&tr[now].r==y) return tr[now].c; else { int lc=tr[now].lc,rc=tr[now].rc; pushdown(now); int mid=(tr[now].l+tr[now].r)>>1; if(y<=mid) return query(lc,x,y); else if(x>=mid+1) return query(rc,x,y); else return query(lc,x,mid)+query(rc,mid+1,y); } } int main() { n=read(); m=read(); for(int i=1;i<=n;i++) a[i]=read(); bt(1,n); for(int i=1;i<=m;i++) { int p,x,y,k; p=read(); if(p==1) { x=read();y=read();k=read(); update(1,x,y,k); }else if(p==2) { x=read();y=read(); printf("%lld\n",query(1,x,y)); } } return 0; }

【洛谷P3372】【模板】線段樹 1