BOJ 16975: 수열과 쿼리 21

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

  • 2월동안 187문제 풀기(지난달 누적 87개) (64/187)
  • 세그먼트 트리, 리뷰용 문제(https://codeforces.com/blog/entry/18051)
  • 앞선 11505번은 point update, range query이고
  • 이번엔 반대로 range update, point query 문제이다.
    • 이 경우 build를 하지 않는다.
    • range update시에는 부분 구간의 root에만 값을 써둔다.
    • point query시에는 쭉 root로 올라가면 부분 구간에 써져있는 값들을 더한 후에 답을 낸다.
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;
}