본문 바로가기

알고리즘/알고리즘 이론, 템플릿

세그트리

ll arr[1000002];
ll tree[4 * 1000002];
ll N, M, K;
ll order;
ll a, b, c, d;

ll init(ll start, ll end, ll node)
{
	if (start == end)
		return tree[node] = arr[start];

	ll mid = (start + end) / 2;

	return tree[node] = init(start, mid, node * 2) + init(mid + 1, end, node * 2 + 1);
}

ll query(ll start, ll end, ll node, ll left, ll right)
{
	if (left > end || right < start)
		return 0;

	if (left <= start && end <= right)
		return tree[node];

	ll mid = (start + end) / 2;

	return query(start, mid, node * 2, left, right) + query(mid + 1, end, node * 2 + 1, left, right);
}

ll update(ll start, ll end, ll node, ll index, ll diff)
{
	if (index < start || end < index)
		return tree[node];

	if (start == end)
		return tree[node] = diff;;

	ll mid = (start + end) / 2;

	return tree[node] = update(start, mid, node * 2, index, diff) + update(mid + 1, end, node * 2 + 1, index, diff);
}

 

'알고리즘 > 알고리즘 이론, 템플릿' 카테고리의 다른 글

shift 연산과 오버플로우  (0) 2023.03.06
에라토스테네스의체  (0) 2023.01.25
컨벡스헐  (0) 2023.01.15
eof 처리  (0) 2022.12.23
유니온 파인드  (0) 2022.12.18