A Simple Problem with IntegersA\ Simple\ Problem\ with\ IntegersA Simple Problem with Integers
Time Limit: 5000/1500 MS (Java/Others) | Memory Limit: 32768/32768 K (Java/Others) |
---|---|
Total Submission(s): 6644 | Accepted Submission(s): 2131 |
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)
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<=10,但还是没想法。看了解析才知道要开55个线段树。因为k<=10,而且(i-a)%k≡0
等价于i%k≡a%k,就是区间[ a , b ]之间所有符合条件的 i 对 k 取模恒等于 a 对 k 取模得到的值,而 a 对 k 取模的情况一共有55种,所以用55棵线段树分别去维护这些模值。
之后查询的时候只要把要查询的点对1~10分别取模,然后对十种情况的线段树分别进行单点查询就好了,空间卡的好死,差点就爆M了,还好A了。
(其实就是一个区间更新,单点查询的问题)
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
static const int maxn = 14e4;
int n,q,tn;
int init[maxn];
int segtree[55][maxn];
int segid(int x,int y){
int id = 0;
for(int i=1;i<x;i++) id+=i;
id+=y;
return id;
}
void update(int id,int l,int r,int k,int tl,int tr,int c){
if(l<=tl&&tr<=r) segtree[id][k] += c;
else if(l>=tr||r<=tl) return;
else{
int mid = (tl+tr)>>1;
update(id,l,r,k*2,tl,mid,c);
update(id,l,r,k*2+1,mid,tr,c);
}
}
int getsum(int id,int l,int r,int k,int tl,int tr){
if(r<=tl||tr<=l) return 0;
else if(tl==l&&tr==r) return segtree[id][k];
else if(tl<=l&&r<=tr) return segtree[id][k] + getsum(id,l,r,k*2,tl,(tl+tr)>>1) + getsum(id,l,r,k*2+1,(tl+tr)>>1,tr);
else return getsum(id,l,r,k*2,tl,(tl+tr)>>1) + getsum(id,l,r,k*2+1,(tl+tr)>>1,tr);
}
int query(int pos){
int res = 0;
for(int i=1;i<=10;i++){
int mod = pos%i;
res+=getsum(segid(i,mod),pos,pos+1,1,1,tn);
}
return res;
}
int main(){
while(scanf("%d",&n)!=EOF){
tn = 1;
while(tn<n) tn<<=1; tn+=1;
memset(segtree,0,sizeof(segtree));
for(int i=1;i<=n;++i) scanf("%d",&init[i]);
scanf("%d",&q);
for(int i=1;i<=q;++i){
int op;
scanf("%d",&op);
if(op==2){
int pos;
scanf("%d",&pos);
printf("%d\n",query(pos)+init[pos]);
}
else if(op==1){
int a,b,k,c;
scanf("%d %d %d %d",&a,&b,&k,&c);
int mod = a%k;
update(segid(k,mod),a,b+1,1,1,tn,c);
}
}
}
return 0;
}