Boj1275_커피숍2

Published: by Creative Commons Licence

boj1275_커피숍2

  • 변경이 빈번한 세그먼트 트리
#include<iostream>
#include<vector>
#include<math.h>
#include<algorithm>
using namespace std;
int n, q,num;
vector<long long> arr,seg;

long long init(int idx, int s, int e) {
	if (s == e) return seg[idx] = arr[s];
	int mid = (s + e) / 2;
	return seg[idx]=init(idx * 2, s, mid)+init(idx*2+1,mid+1,e);
}

long long query(int idx, int L, int R, int i, int j) { //i,j가 내가 원하는 값
	if (L > j || R < i) return 0;
	if (i <= L && R <= j) return seg[idx];
	int mid = (L + R) / 2;
	return query(idx * 2, L, mid, i, j) + query(idx * 2 + 1, mid + 1, R, i, j);
}
void update(int idx, long long diff) {
	seg[idx] -= diff;
	if (idx == 1) return;
	update(idx / 2, diff);
}

int main() {
	scanf("%d %d", &n, &q);
	int h = (int)ceil(log2(n));
	int size = (1 << (h + 1)) - 1;
	arr.resize((size+1) / 2);
	seg.resize(size + 1);
	for (int i = 0; i < n; i++) {
		scanf("%lld", &arr[i]);
	}
	init(1, 0,(size+1)/2-1);

	for (int i = 0; i < q; i++){
		int a, b, x, y;
		scanf("%d %d %d %d", &a, &b, &x, &y);
		printf("%lld\n",query(1,0,(size+1)/2-1,min(a-1,b-1), max(a-1,b-1)));
		update(x+(size+1)/2-1, (long long)arr[x-1] - y);
		arr[x-1] = y;
	}


}