HDU - 4267 A Simple Problem with Integers(树状数组的逆操作)
Description
Input
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
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
思路:用树状数组做,但是和一般的树状数组不一样,这里是将sum和add操作交换了(这点需要好好理解一下,我们通过两次的以前的sum操作将区间[a, b]赋值,然后再通过以前的add操作找到可以影响到它的结点求总的操作值),将取模公式转换成:i%k=a%k,那么我们注意到k是比较小的,所以我们可以先记录a%k时操作的结果,也就是开arr[x][k][a%k]表示,最后再求和计算x坐标的结果是枚举余数就行了
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 50005; int arr[maxn][11][11]; int n, num[maxn]; inline int lowbit(int x) { return x & (-x); } inline void Add(int x, int k, int mod, int c){ while (x > 0) { arr[x][k][mod] += c; x -= lowbit(x); } } inline int sum(int x, int a) { int ans = 0; while (x < maxn) { for (int i = 1; i <= 10; i++){ ans += arr[x][i][a%i]; } x += lowbit(x); } return ans; } int main() { while (scanf("%d", &n) != EOF) { for (int i = 1; i <= n; i++) scanf("%d", &num[i]); memset(arr, 0, sizeof(arr)); int m; scanf("%d", &m); while (m--) { int op, a, b, k, c; 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); int ans = sum(a, a); printf("%d\n", ans + num[a]); } } } return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。