poj3468 A Simple Problem with Integers (树状数组做法)
Posted zhgyki
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj3468 A Simple Problem with Integers (树状数组做法)相关的知识,希望对你有一定的参考价值。
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 142198 | Accepted: 44136 | |
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<iostream>
#include<string.h>
using namespace std;
typedef long long ll;
#define MAX 100005
int n,q;
int a[MAX];
ll bit0[MAX],bit1[MAX];
void updata(ll *b,int i,int val)
{
while(i<=n)
{
b[i]+=val;
i+=i&-i;
}
}
ll query(ll *b,int i)
{
ll res=0;
while(i>0)
{
res+=b[i];
i-=i&-i;
}
return res;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
while(cin>>n>>q)
{
memset(bit0,0,sizeof(bit0));
memset(bit1,0,sizeof(bit1));
for(int i=1;i<=n;i++)
{
cin>>a[i];
updata(bit0,i,a[i]);
}
while(q--)
{
int l,r,x;
char ch;
cin>>ch;
cin>>l>>r;
if(ch==‘C‘)
{
cin>>x;
updata(bit0,l,-x*(l-1));
updata(bit1,l,x);
updata(bit0,r+1,x*r);
updata(bit1,r+1,-x);
}
else
{
ll sum=0;
sum+=query(bit0,r)+query(bit1,r)*r;
sum-=query(bit0,l-1)+query(bit1,l-1)*(l-1);
cout<<sum<<endl;
}
}
}
}
以上是关于poj3468 A Simple Problem with Integers (树状数组做法)的主要内容,如果未能解决你的问题,请参考以下文章
A Simple Problem with Integers POJ - 3468
POJ - 3468 A Simple Problem with Integers
[poj3468]A Simple Problem with Integers
POJ3468 a simple problem with integers 分块