A Simple Problem with Integers
Time Limit: 5000/1500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3480 Accepted Submission(s): 1076
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
Source
解题思路:注意到k最大只有10,那么开tree[10][11][Maxn]这样的树状数组记录下tree[a%k][k][pos]的更新,维护的时候查一下j从1到10,tree[a%j][j][pos]的情况这样最后就是结果。
#include <iostream>
#include <cstdio>
#include <cstring>
#define Maxn 50005
#define lowbit(x) x&(-x)
using namespace std;
int tree[10][11][Maxn];
void add(int mod,int k,int pos,int c,int n)
{
for(int i=pos;i<=n;i+=lowbit(i))
tree[mod][k][i]+=c;
}
int sum(int a,int pos)
{
int ans=0;
for(int i=pos;i>0;i-=lowbit(i))
for(int j=1;j<=10;j++)
ans+=tree[a%j][j][i];
return ans;
}
int main()
{
int n,q,a,b,c,k,t;
int arr[Maxn];
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
while(~scanf("%d",&n))
{
memset(tree,0,sizeof(tree));
for(int i=1;i<=n;i++)
scanf("%d",arr+i);
scanf("%d",&q);
while(q--)
{
scanf("%d",&t);
if(t==1)
{
scanf("%d%d%d%d",&a,&b,&k,&c);
add(a%k,k,a,c,n);
add(a%k,k,b+1,-c,n);
}
else
{
scanf("%d",&a);
printf("%d\n",sum(a,a)+arr[a]);
}
}
}
return 0;
}