A Simple Problem with Integers
Posted 勿忘初心0924
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了A Simple Problem with Integers相关的知识,希望对你有一定的参考价值。
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 99895 | Accepted: 31162 | |
Case Time Limit: 2000MS |
Description
You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.
Input
The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
10 5 1 2 3 4 5 6 7 8 9 10 Q 4 4 Q 1 10 Q 2 4 C 3 6 3 Q 2 4
Sample Output
4 55 9 15
Hint
Source
/* 手敲模板结果各种手残! */ #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #define N 100010 #define ll long long #define lson i*2,l,m #define rson i*2+1,m+1,r using namespace std; /* 线段树区间更新的时候将更新值存入数组add数组中,等你需要的再去加到sum数组中 */ ll sum[N*4]; ll add[N*4]; void pushdown(int i,int num)///向下更新 { if(add[i])///等于0的话没有更新的必要了 { sum[i*2] += add[i]*(num-(num/2)); sum[i*2+1] += add[i]*(num/2); add[i*2]+=add[i]; add[i*2+1]+=add[i]; add[i]=0;///这个节点的信息更新完了,那么相应的存在add数组中的东西就没有了 } } void pushup(int i)///向下更新 { sum[i]=sum[i*2]+sum[i*2+1]; } void build(int i,int l,int r) { add[i]=0;///将每个节点更新的值初始化为0 if(l==r) { scanf("%lld",&sum[i]); //cout<<sum[i]<<" "; return ; } int m=(l+r)/2; build(lson); build(rson); pushup(i); } void update(int ql,int qr,int val,int i,int l,int r) { if(ql<=l&&r<=qr) { add[i]+=val; sum[i]+=(ll)val*(r-l+1); return ; } pushdown(i,r-l+1); int m=(l+r)/2; if(ql<=m) update(ql,qr,val,lson); if(m<qr) update(ql,qr,val,rson); pushup(i); } ll query(int ql,int qr,int i,int l,int r) { //cout<<"l="<<l<<" r="<<r<<endl; if(ql<=l&&r<=qr) { return sum[i]; } pushdown(i,r-l+1); int m=(l+r)/2; ll cur=0; if(ql<=m) cur+=query(ql,qr,lson); if(m<qr) cur+=query(ql,qr,rson); return cur; } int main() { //freopen("C:\\Users\\acer\\Desktop\\in.txt","r",stdin); int n,q; char op; while(scanf("%d%d",&n,&q)!=EOF) { //cout<<n<<" "<<m<<endl; build(1,1,n); //for(int i=1;i<=(n*(n+1)/2);i++) // cout<<sum[i]<<" "; //cout<<endl; //cout<<endl; int a,b,c; getchar(); while(q--) { scanf("%c",&op); //cout<<op<<" "; if(op==‘Q‘) { scanf("%d%d",&a,&b); //cout<<a<<" "<<b<<endl; //cout<<"Q"<<endl; printf("%lld\n",query(a,b,1,1,n)); } else { scanf("%d%d%d",&a,&b,&c); //cout<<"C"<<endl; update(a,b,c,1,1,n); } getchar(); } } return 0; }
以上是关于A Simple Problem with Integers的主要内容,如果未能解决你的问题,请参考以下文章
POJ3468A Simple Problem with Integers
线段树专题 POJ3468 A Simple Problem with Integers
A Simple Problem with Integers
A Simple Problem with Integers