洛谷 P3368 樹狀數組(區間修改 單點查詢)

就是區間修改和單點查詢,這個題目可以用來檢查自己寫的對不對

#include <iostream>
#define lowbit(x) (x)&(-(x))
using namespace std;
int n;
int c[5000005];
int a[5000005];
void update(int x, const int & val) {
	while (x <= n) {
		c[x] += val;
		x += lowbit(x);
	}
}
int sum(int x) {
	int ans = 0;
	while (x > 0) {
		ans += c[x];
		x -= lowbit(x);
	}
	return ans;
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	int m;
	cin >> n >> m;
	for (int i = 1; i <= n; ++i) {
		cin >> a[i];
		update(i, a[i] - a[i - 1]);
	}
	int b, x, y, k;
	for (int i = 0; i < m; ++i) {
		cin >> b >> x;
		switch (b)
		{
		case 1:
			cin >> y >> k;
			update(x, k);
			update(y + 1, -k);
			break;
		case 2:
			cout << sum(x) << endl;
			break;
		default:
			break;
		}
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章