題目鏈接:https://vjudge.net/contest/186273#problem/D
Problem Description
秋實大哥以賙濟天下,鋤強扶弱爲己任,他常對天長嘆:安得廣廈千萬間,大庇天下寒士俱歡顏。
所以今天他又在給一羣小朋友發糖喫。
他讓所有的小朋友排成一行,從左到右標號。在接下去的時間中,他有時會給一段區間的小朋友每顆糖,有時會問第x個小朋友手裏有幾顆糖。
這對於沒上過學的孩子來說實在太困難了,所以你看不下去了,請你幫助小朋友回答所有的詢問。
Input
第一行包含兩個整數n,m,表示小朋友的個數,以及接下來你要處理的操作數。
接下來的mm行,每一行表示下面兩種操作之一:
0 l r v : 表示秋實大哥給[l,r]這個區間內的小朋友每人v顆糖
1 x : 表示秋實大哥想知道第x個小朋友手裏現在有幾顆糖
1≤m,v≤100000,1≤l≤r≤n,1≤x≤n,1≤n≤100000000。
Output
對於每一個1 x操作,輸出一個整數,表示第x個小朋友手裏現在的糖果數目。
Sample Input
3 4
0 1 3 1
1 2
0 2 3 3
1 3
Sample Output
1
4
代碼:
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
#define N 100000+10
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
ll sum[N<<2],add[N<<2];
struct Node
{
int l,r;
int mid()
{
return (l+r)>>1;
}
}tree[N<<2];
void PushUp(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
tree[rt].l=l;
tree[rt].r=r;
add[rt]=0;
if(l==r)
{
// scanf("%I64d",&sum[rt]);
sum[rt]=0;
return;
}
int m=tree[rt].mid();
build(lson);
build(rson);
PushUp(rt);//rt從大到小往上返
}
void PushDown(int rt,int m)
{
if(add[rt])
{
add[rt<<1]+=add[rt];
add[rt<<1|1]+=add[rt];
sum[rt<<1]+=add[rt]*(m-(m>>1));
sum[rt<<1|1]+=add[rt]*(m>>1);
add[rt]=0;
}
}
ll query(int l,int r,int rt)
{
if(l==tree[rt].l&&r==tree[rt].r)
{
return sum[rt];
}
PushDown(rt,tree[rt].r-tree[rt].l+1);
int m=tree[rt].mid();
ll res=0;
if(r<=m)
{
res+=query(l,r,rt<<1);
}
else if(l>m)
{
res+=query(l,r,rt<<1|1);
}
else
{
res+=query(l,m,rt<<1);
res+=query(rson);
}
return res;
}
void update(int c,int l,int r,int rt)
{
if(tree[rt].l==l&&tree[rt].r==r)
{
add[rt]+=c;
sum[rt]+=(ll)c*(r-l+1);
return ;
}
if(tree[rt].l==tree[rt].r)
{
return ;
}
PushDown(rt,tree[rt].r-tree[rt].l+1);
int m=tree[rt].mid();
if(r<=m)
{
update(c,l,r,rt<<1);
}
else if(l>m)
{
update(c,l,r,rt<<1|1);
}
else
{
update(c,l,m,rt<<1);
update(c,m+1,r,rt<<1|1);
}
PushUp(rt);
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
build(1,n,1);
while(m--)
{
char ch[2];
scanf("%s",ch);
int a,b,c;
if(ch[0]=='1')
{
scanf("%d",&a);
printf("%lld\n",query(a,a,1));
}
else
{
scanf("%d%d%d",&a,&b,&c);
update(c,a,b,1);
}
}
}
return 0;
}