반응형
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);
	}
};
반응형

+ Recent posts