A Simple Problem with Integers
Time Limit: 5000/1500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7087 Accepted Submission(s): 2243
Problem Description
Let A1, A2, ... , AN be N elements. You need to deal with two kinds of operations. One type of operation is to add a given number to a few numbers in a given interval. The other is to query the value of some element.
Input
There are a lot of test cases.
The first line contains an integer N. (1 <= N <= 50000)
The second line contains N numbers which are the initial values of A1, A2, ... , AN. (-10,000,000 <= the initial value of Ai <= 10,000,000)
The third line contains an integer Q. (1 <= Q <= 50000)
Each of the following Q lines represents an operation.
"1 a b k c" means adding c to each of Ai which satisfies a <= i <= b and (i - a) % k == 0. (1 <= a <= b <= N, 1 <= k <= 10, -1,000 <= c <= 1,000)
"2 a" means querying the value of Aa. (1 <= a <= N)
The first line contains an integer N. (1 <= N <= 50000)
The second line contains N numbers which are the initial values of A1, A2, ... , AN. (-10,000,000 <= the initial value of Ai <= 10,000,000)
The third line contains an integer Q. (1 <= Q <= 50000)
Each of the following Q lines represents an operation.
"1 a b k c" means adding c to each of Ai which satisfies a <= i <= b and (i - a) % k == 0. (1 <= a <= b <= N, 1 <= k <= 10, -1,000 <= c <= 1,000)
"2 a" means querying the value of Aa. (1 <= a <= N)
Output
For each test case, output several lines to answer all query operations.
Sample Input
4 1 1 1 1 14 2 1 2 2 2 3 2 4 1 2 3 1 2 2 1 2 2 2 3 2 4 1 1 4 2 1 2 1 2 2 2 3 2 4
Sample Output
1 1 1 1 1 3 3 1 2 3 4 1
数组的第一维代表的是树状数组,树状数组的每个节点保存的是一个二维矩阵。因为k的值很小,i%k的值也很小,所以可以实现这个二维矩阵。初始化建立的是初值都为0的树状数组,在最后计算结果时,再加上a[i]的初始值。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
int a[50010];
int c[50010][11][11];
int lowbit(int i) {
return i&(-i);
}
void updata(int x,int k,int mod,int data) {
while(x<=n){
c[x][k][mod]+=data;
x+=lowbit(x);
}
}
int query(int x,int y) {
int res=0,i;
while(x>0){
for(i=1;i<=10;i++){
res+=c[x][i][y%i];
}
x-=lowbit(x);
}
return res;
}
int main(){
int i,j;
int x,q;
int s,y,k,data;
while(~scanf("%d",&n)){
memset(c, 0, sizeof(c));
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
scanf("%d",&q);
while(q--){
scanf("%d",&x);
if(x==1){
scanf("%d%d%d%d",&s,&y,&k,&data);
updata(s,k,s%k,data);
updata(y+1,k,s%k,-data);
}
else{
scanf("%d",&y);
int ans=query(y,y);
cout<<(ans+a[y])<<endl;
}
}
}
return 0;
}