首页 > 代码库 > A Simple Problem with Integers_树状数组
A Simple Problem with Integers_树状数组
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
【题意】给出n个数,再给出m个操作
1.op==1,输入四个数据a,b,k,c将区间[a,b]中的数i满足(i-a)%k == 0加上c.
2.op==2,输入一个数y,输出序列中第y个数的值。
被这题虐哭,(毕竟太弱了~~)关键就是建立多个树状数组,然而我对树状数组理解还是不行啊!
sum[x][k][x%k]代表x对k取余的值,然后每次更新树状数组的时候只需要更新update(a,.....) 与update(b+1,.....);
参考资料:http://blog.csdn.net/yeguxin/article/details/47999833
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int N=50000+10; int aa[N]; int n,m; int sum[N][12][12];//开稍大一点就会MLE int lowbit(int x) { return x&(-x); } void update(int x,int k,int mod,int v) { while(x<=n) { sum[x][k][mod]+=v; x+=lowbit(x); } } int query(int x,int y) { int res=0; while(x) { for(int i=1;i<=10;i++) { res+=sum[x][i][y%i]; } x-=lowbit(x); } return res; } int main() { while(~scanf("%d",&n)) { memset(sum,0,sizeof(sum)); for(int i=1;i<=n;i++) { scanf("%d",&aa[i]); } scanf("%d",&m); int op,a,b,k,c; while(m--) { scanf("%d",&op); if(op==2) { scanf("%d",&k); int ans=query(k,k); printf("%d\n",ans+aa[k]); } else if(op==1) { scanf("%d%d%d%d",&a,&b,&k,&c); int kk=(b-a)/k; update(a,k,a%k,c); update(b+1,k,a%k,-c); } } } return 0; }
A Simple Problem with Integers_树状数组
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。