1. 程式人生 > >HDU1166樹狀陣列裸題

HDU1166樹狀陣列裸題

1.題意就不在介紹,只放一張圖和AC程式碼,因為這個東西的思想和線段樹有異曲同工之妙,所以不是太懂的只需要看一下線段樹是怎麼實現的。

 樹狀陣列

#include"stdafx.h"
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
const int maxx = 50010;
int c[maxx];
int n;
//這個lowerbit的解釋可以有很多種,我們就採用一種簡單的解釋方法
//lowerbit函式就是為了找出這樣一個數:假設這個數的二進位制資料是10000,那麼我們要找的就是pow(2,4).
//因為從低位到高位連續有4個0,所以就是2的4次冪。沒錯,連續有幾個0就是2的幾次冪。
int lowbit(int k) { return k & (-k); }
//這是在點更新
void add(int x, int y) {
	while (x <= n) {
		c[x] += y;
		x += lowbit(x);
	}
	return;
}
//這是在預處理字首和
int sum(int x) {
	int sum = 0;
	while (x > 0) {
		sum += c[x];
		x -= lowbit(x);
	}
	return sum;
}
int main() {
	int T, x, y, xu = 1;
	string s;
	cin >> T;
	while (T--) {
		memset(c, 0, sizeof(int)*maxx);
		printf("Case %d:\n", xu++);
		cin >> n;
		for (int i = 1; i <= n; i++) {
			cin >> x;
			add(i, x);
		}
		while (1) {
			cin >> s;
			if (s[0] == 'E') break;
			else if (s[0] == 'A') {
				cin >> x >> y;
				add(x, y);
			}
			else if (s[0] == 'S') {
				cin >> x >> y;
				add(x, -y);
			}
			else if (s[0] == 'Q') {
				cin >> x >> y;
				cout << sum(y) - sum(x - 1) << endl;
			}
		}
	}
	return 0;
}