반응형
struct SegmentTree {
int N;
vector<int> tree;
int merge(int left, int right) {
return left + right;
}
int buildRec(const int arr[], int node, int nodeLeft, int nodeRight) {
if (nodeLeft == nodeRight)
return tree[node] = arr[nodeLeft];
int mid = (nodeLeft + nodeRight) / 2;
int leftVal = buildRec(arr, node * 2, nodeLeft, mid);
int rightVal = buildRec(arr, node * 2 + 1, mid+1, nodeRight);
return tree[node] = merge(leftVal, rightVal);
}
void build(const int arr[], int Size) {
N = Size;
tree.resize(N*4);
buildRec(arr, 1, 0, N - 1);
}
int queryRec(int left, int right, int node, int nodeLeft, int nodeRight) {
if (nodeRight < left || right < nodeLeft) return 0;
if (left <= nodeLeft && nodeRight <= right) return tree[node];
int mid = (nodeLeft + nodeRight) / 2;
int leftVal = queryRec(left, right, node * 2, nodeLeft, mid);
int rightVal = queryRec(left, right, node * 2 + 1, mid + 1, nodeRight);
return merge(leftVal, rightVal);
}
int query(int left, int right) {
return queryRec(left, right, 1, 0, N - 1);
}
// 하나만 업데이트
int updateRec(int index, int newValue, int node, int nodeLeft, int nodeRight) {
if (index < nodeLeft || nodeRight < index) {
return tree[node];
}
if (nodeLeft == nodeRight) {
return tree[node] = newValue;
}
int mid = (nodeLeft + nodeRight) / 2;
int updateLeft = updateRec(index, newValue, node*2, nodeLeft, mid);
int updateRight = updateRec(index, newValue, node*2+1, mid + 1, nodeRight);
return tree[node] = merge(updateLeft, updateRight);
}
int update(int index, int newValue) {
return updateRec(index, newValue, 1, 0, N - 1);
}
// 여러개 업데이트
int updateRec(int left, int right, int newValue, int node, int nodeLeft, int nodeRight) {
if (nodeRight < left || right < nodeLeft) {
return tree[node];
}
if (nodeLeft == nodeRight) {
return tree[node] = newValue;
}
int mid = (nodeLeft + nodeRight) / 2;
int updateLeft = updateRec(left,right, newValue, node * 2, nodeLeft, mid);
int updateRight = updateRec(left,right, newValue, node * 2 + 1, mid + 1, nodeRight);
return tree[node] = merge(updateLeft, updateRight);
}
int update(int left, int right, int newValue) {
return updateRec(left , right, newValue, 1, 0, N - 1);
}
};
반응형
'Algorithm > etc' 카테고리의 다른 글
Network FLow 최대 유량 알고리즘 (0) | 2022.02.22 |
---|---|
cycle 찾기 (0) | 2022.02.21 |
플로이드 워샬 알고리즘이란? (냅색 응용) -모든 정점의 최단 거리 구하기 (0) | 2022.01.28 |
냅색 알고리즘(한번 만 사용가능) 2차원, 1차원 배열 (0) | 2022.01.26 |
냅색 문제 (0) | 2022.01.26 |