A Simple Problem with Integers
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
The sums may exceed the range of 32-bit integers.
题意:
给定Q (1 ≤ Q ≤ 100,000)个数A1,A2 … AQ,,
以及可能多次进行的两个操作:
- 对某个区间Ai … Aj的每个数都加n(n可变)
- 求某个区间Ai … Aj的数的和
思路:
题目所给数据太大,用一般方法一定会超时;
本题就是线段树模板题,对着模板打就行了,
数据太大,int型存不下,用long long。
如果还不太懂线段树,可以看看这篇博客(https://www.cnblogs.com/jason2003/p/9676729.html)
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define maxx 400010
#define ll long long
ll sum[maxx],book[maxx];
void build(int x,int y,int o)//建树
{
if(x==y)
{
scanf("%lld",&sum[o]);
return;
}
int mid=(x+y)>>1;
build(x,mid,o<<1);
build(mid+1,y,o<<1|1);
sum[o]=sum[o<<1]+sum[o<<1|1];
}
void pust(int v,int u,int o)
{
if(book[o]!=0)
{
book[o<<1]+=book[o];//标记左子节点
book[o<<1|1]+=book[o];//右子节点
int k=u-v+1;
sum[o<<1]+=(k-(k>>1))*book[o];//更新o节点的左子节点
sum[o<<1|1]+=(k>>1)*book[o];//右子节点
book[o]=0;//取消标记
}
}
ll queu(int a,int b,int c,int d,int o)
{
if(a<=c&&b>=d)
return sum[o];
pust(c,d,o);
int mid=(c+d)>>1;
ll sum=0;
if(a<=mid)sum+=queu(a,b,c,mid,o<<1);
if(b>mid)sum+=queu(a,b,mid+1,d,o<<1|1);
return sum;
}
void upset(int a,int b,int c,int n,int m,int o)
{
if(a<=n&&b>=m)//若该区间在要更新的区间,更新区间,并标记
{
sum[o]=sum[o]+(m-n+1)*c;
book[o]+=c;
return ;
}
pust(n,m,o);//更新其他子节点
int mid=(n+m)>>1;
if(a<=mid)upset(a,b,c,n,mid,o<<1);
if(b>mid)upset(a,b,c,mid+1,m,o<<1|1);
sum[o]=sum[o<<1]+sum[o<<1|1];
}
int main()
{
int n,m,i,j;
scanf("%d%d",&n,&m);
memset(sum,0,sizeof(sum));
memset(book,0,sizeof(book));
build(1,n,1);
while(m--)
{
char a[20];
int k,t,x,y,z;
scanf("%s",a);
if(a[0]=='Q')
{
scanf("%d%d",&k,&t);
ll sum1=queu(k,t,1,n,1);
printf("%lld\n",sum1);
}
else
{
scanf("%d%d%d",&x,&y,&z);
upset(x,y,z,1,n,1);
}
}
}