BOJ 10999: 구간 합 구하기 2

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

  • 2월동안 187문제 풀기(지난달 누적 87개) (67/187)
  • 드디어 풀어본 Lazy Propagation
    • 이걸 진짜 외워서 적을 수 있나 의심이 든다.
    • 일단 생성자에서 트리의 높이h를 구해놔야 한다. Count Leading Zero를 이용한다. 물론 그냥 while loop 돌아도 된다.
    • d 배열이 lazy 배열이다.
    • d는 N 사이즈만 준다. leaf 들에는 lazy가 필요 없기 때문
    • build(위로 올라가면서 업데이트), push(아래로 내려가면서 lazy 해소)
    • range update
      • 부분구간의 root에다가만 값을 써놓는다.
      • root가 포함하는 leaf의 개수를 이용해서 값을 계산하고, lazy에도 값을 써둔다.
      • 부분 구간의 root들을 집합 S라고 하면 이 S들의 부모들에다가도 값을 써줘야 한다.
      • 양쪽 끝점에서 build를 이용해서 위로 올라가면 S들의 부모들을 모두 업데이트 할 수 있다. (그림을 그려보면 무조건 그렇다. 왜그런지 모르겟…)
    • range query
      • push를 통해서 아래로 내려가면서 lazy를 해소한다. lazy는 저 위에서 아래로 영향을 주기 때문에 반드시 하향해야 한다.
      • 위에서랑 마찬가지로 양쪽 끝을 기준으로 내려오면 부분구간의 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <bits/stdc++.h>
using namespace std;

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

  SegmentTree(int n) : N(n), t(2*n), d(n) {
    for(int i = N; i < 2*N; i++)
      scanf("%lld", &t[i]);
    h = sizeof(n) * 8 - __builtin_clz(n);
    for (int i = N-1; i > 0; i--)
      t[i] = t[2*i] + t[2*i+1];
  }

  void apply(int p, LL v, LL children) {
    t[p] += v * children;
    if(p < N) d[p] += v;
  }

  void build(int p) {
    for(LL children = 2; p > 1; p/=2, children*=2)
      t[p/2] = t[p] + t[p^1] + d[p/2]*children;
  }

  void push(int p) {
    for(int s = h; s > 0; --s) {
      int i = p >> s;
      if(d[i] == 0) continue;
      LL children = 1 << (s-1);
      apply(i*2, d[i], children);
      apply(i*2+1, d[i], children);
      d[i] = 0;
    }
  }

  void update(int l, int r, LL v) {
    l += N, r += N;
    int l0 = l, r0 = r;
    for(LL children = 1; l < r; l/=2, r/=2, children*=2) {
      if(l&1) apply(l++, v, children);
      if(r&1) apply(--r, v, children);
    }
    build(l0), build(r0-1);
  }

  LL query(int l, int r) {
    push(l+N); push(r+N-1);
    LL res = 0;
    for(l += N, r += N; l < r; l /= 2, r /= 2) {
      if(l&1) res += t[l++];
      if(r&1) res += t[--r];
    }
    return res;
  }
};

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