BOJ 12899: 데이터 구조

https://www.acmicpc.net/problem/12899

  • 2월동안 187문제 풀기(지난달 누적 87개) (65/187)
  • 펜윅 트리 써서 위치를 마킹해두는 유형의 문제.
  • 나는 누적값이 바뀌는 위치를 바이너리 서치로 찾아서 $O(\log^2{N})$ 만큼 쿼리당 처리 시간이 든다.
  • 쿼리당 처리 시간을 줄이려면 펜윅 트리를 확실하게 이해해야 하는것 같다. 쌓아가면서 절반씩 나눈 값을 조회하면 된다.
    1
    2
    3
    4
    5
    6
    7
    int ans = 0;
    for(int e = (1<<20); e > 0; e /= 2) {
      if (tree[ans] < target) {
        target -= tree[ans];
        ans += e;
      }
    }
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
struct SegmentTree {
  int N;
  vector<LL> t;

  LL INIT = 0;
  inline LL f(LL a, LL b) {
    return a+b;
  }

  SegmentTree(int n) : N(n), t(2*n) {
    for(int i = N; i < 2*N; i++)
      scanf("%lld", &t[i]);
  }

  void update(int l, int r, int v) {
    LL res = INIT;
    for(l += N, r += N; l < r; l /= 2, r /= 2) {
      if(l&1) t[l] = f(v, t[l]), l++;
      if(r&1) --r, t[r] = f(v, t[r]);
    }
  }

  LL query(int p) {
    LL res = INIT;
    for (p += N; p > 0; p /= 2)
      res = f(res, t[p]);
    return res;
  }
};

int main() {
  int N, M, a,b,c;
  scanf("%d", &N);
  SegmentTree seg(N);
  scanf("%d", &M);
  for(int i = 0; i < M; i++) {
    scanf("%d", &a);
    if(a == 1) {
      scanf("%d %d %d", &a, &b, &c);
      seg.update(a-1, b, c);
    } else if(a == 2) {
      scanf("%d", &b);
      printf("%lld\n", seg.query(b-1));
    }
  }
  return 0;
}