A Simple Problem with Integers
Time Limit: 5000/1500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3924 Accepted Submission(s): 1213
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解决方案:本题可用树状数组来做,可是更新线段的时候有个限定的条件a<=i<=b,且(i-a)%k==0,如果单点的话时间复杂度是很高的。所以我们可以做个多状态的树状数组C[i][k][mod],表示除k,余mod,a%k==mod,更新的是(b,k,a%k,c)表示1到b全加c,(a-1,k,a%k,-c)表示1到(a-1)减c,状态时k、a%k。由于(i-a)%k==0查询的时候可以枚举1到10这几个k值,把所有相关状态加起来即可。code:#include <iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn=55000; int C[maxn][11][11],n; int num[maxn]; void add(int x,int k,int mod,int v) { while(x>0) { C[x][k][mod]+=v; x-=(x&(-x)); } } int query(int x,int a) { int ret=0; while(x<=n) { for(int i=1; i<=10; i++) ret+=C[x][i][a%i]; x+=(x&(-x)); } return ret; } int main() { while(~scanf("%d",&n)) { int q,op,a,b,k,c; memset(C,0,sizeof(C)); for(int i=1; i<=n; i++) { scanf("%d",&num[i]); } scanf("%d",&q); for(int i=1; i<=q; i++) { scanf("%d",&op); if(op==1) { scanf("%d%d%d%d",&a,&b,&k,&c); add(b,k,a%k,c); add(a-1,k,a%k,-c); } else { scanf("%d",&a); printf("%d\n",query(a,a)+num[a]); } } } return 0; }