码迷,mamicode.com
首页 > 编程语言 > 详细

HDU - 4267 A Simple Problem with Integers(树状数组的逆操作)

时间:2014-10-18 16:59:56      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   io   os   ar   for   sp   div   

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
题意:给你两个操作1 a b k c代表的是将区间[a, b]之间的能使得(i-a)%k = 0的数加上c,2 a是查询值

思路:用树状数组做,但是和一般的树状数组不一样,这里是将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;  
}



HDU - 4267 A Simple Problem with Integers(树状数组的逆操作)

标签:des   style   color   io   os   ar   for   sp   div   

原文地址:http://blog.csdn.net/u011345136/article/details/40211831

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!