๋ฐฑ์ค 2042: ๊ตฌ๊ฐ ํฉ ๊ตฌํ๊ธฐ
https://www.acmicpc.net/problem/2042
์ ๊ทผ ๋ฐฉํฅ ๋ฐ ๋๋ฒ๊น
"๋ฒ์" ๋ณ ์ฌ๊ท ํธ๋ค๋ง์ ์ง์ค
[1] ์ฐพ๋ ๋ฒ์๋ฅผ ๋ฏธํฌํจํ๋ ํธ์ถ์ผ ๋
[2] ์ฐพ๋ ๋ฒ์๋ฅผ ์ ๋ถ ํฌํจํ๋ ํธ์ถ์ผ ๋
[3] ์ฐพ๋ ๋ฒ์๋ฅผ ์ผ๋ถ ํฌํจํ๋ ํธ์ถ์ผ ๋
์ ์ํ ๋ฐ์ดํฐ ํ์ ๊ณ ๋ฏผ
- ๋ฌธ์ ์กฐ๊ฑด ์ค "์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง๋ ๋ชจ๋ ์๋ -263๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๊ณ , 263-1๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ ์ ์์ด๋ค." ์ ๋ณด๊ณ ๋ชจ๋ ์ ์ํ ์๋ฃํ์ long long ์ผ๋ก ์ ์ธํ์ฌ ์ฌ์ฉ
- ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ ํจ์จ์ ์ผ๋ก ์ฌ์ฉํ๊ธฐ ์ํด int ๋ก ์ ์งํ ์ ์๋ ๋ณ์๋ค์ ๋ค์ int ๋ก ๋ฐ๊ฟจ์ผ๋ ๊ฒฐ๊ณผ์ ์ผ๋ก ๋ฉ๋ชจ๋ฆฌ๊ฐ ์ค์ง๋ ์์. (์๋ง ์ฑ์ ํ๊ฒฝ์์ int ๊ฐ 8 byte ์ฌ์ ๊ทธ๋ฐ๊ฐ๋ด)
์ฝ๋
/* 87960KB, 220ms */
#include <iostream>
#include <stdio.h>
#define MAX 1000001
#define MAXSEG 10000001
using namespace std;
long long numArr[MAX];
long long segArr[MAXSEG];
long long segTree(int node, int start, int end) {
if (start == end) {
return segArr[node] = numArr[start];
}
int mid = (start + end) / 2;
long long l = segTree(node * 2, start, mid);
long long r = segTree(node * 2 + 1, mid + 1, end);
return segArr[node] = l + r;
}
long long findSum(int node, int start, int end, int findStart, int findEnd) {
if (findStart > end || findEnd < start) return 0;
if (findStart <= start && findEnd >= end) return segArr[node];
int mid = (start + end) / 2;
long long l = findSum(node * 2, start, mid, findStart, findEnd);
long long r = findSum(node * 2 + 1, mid + 1, end, findStart, findEnd);
return l + r;
}
void updateNode(int node, int start, int end, int idx, long long diff) {
if (idx > end || idx < start) return;
segArr[node] += diff;
if (start != end) {
int mid = (start + end) / 2;
updateNode(node * 2, start, mid, idx, diff);
updateNode(node * 2 + 1, mid + 1, end, idx, diff);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
freopen("input.txt", "r", stdin);
int N, M, K;
cin >> N >> M >> K;
for (int i = 0; i < N; i++) {
cin >> numArr[i];
}
segTree(1, 0, N - 1);
while (M || K) {
long long a, b, c;
cin >> a >> b >> c;
if (a == 1) {
updateNode(1, 0, N - 1, b - 1, c - numArr[b - 1]);
numArr[b - 1] = c;
M--;
}
else {
long long res = findSum(1, 0, N - 1, b - 1, c - 1);
cout << res << "\n";
K--;
}
}
return 0;
}
๋ฐฐ์ด ์
- return segArr[node] = numArr[start]; ๊ฐ ๊ฐ๋ฅํ๋ค๋ ๊ฒ
- segTree ์ ํฌ๊ธฐ๋ ๋ฐฐ์ด ํฌ๊ธฐ N ๋ณด๋ค ์ปค์ผ ํ๋ค๋ ๊ฒ
ใด segTree ๋์ด: ceil(log2(N))
ใด segTree ํฌ๊ธฐ: 2 ^ (๋์ด + 1)
'๐ป DEV > Algorithms & Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๊ณ ๋ฆฌ์ฆ][C++] ํธ๋ผ์ด (Trie) (0) | 2024.03.13 |
---|---|
[์๊ณ ๋ฆฌ์ฆ][C++] ์ฐ์ ์์ํ, ํํ (0) | 2024.03.11 |
[์๊ณ ๋ฆฌ์ฆ][C++] Dijkstra (๋ค์ต์คํธ๋ผ) / ์ต๋จ ๊ฒฝ๋ก ํ์ (0) | 2024.03.11 |
[Algorithms] ์๊ฐ๋ณต์ก๋ (Big-O Notation) ๋? (0) | 2021.07.08 |
[Data Structure] ์คํ(Stack) ๊ณผ ํ(Queue) (0) | 2021.07.07 |
๋๊ธ