Post

2268 (수들의 합 7)

2268 (수들의 합 7)

3/4 (월) - Fenwick/SegTree 선택 훈련

오늘 문제

  • [[2268 (수들의 합 7)]]

오늘 목표

  • 핵심 아이디어를 스스로 설명할 수 있을 정도로 정리
  • 풀이 후 시간복잡도/병목 구간 점검

체크리스트

  • 1회 정답 제출
    • 4회 제출
  • 핵심 로직 3줄 요약
  • 오답/실수 포인트 기록

풀이 메모

  • 병목 포인트는 Modify 구현
    • 처음에는 아래까지 쭉 내려갔다가 다시 올라오는 식으로 구현
    • 지금은 diff를 미리 구한 후 한 번 내려가면 끝나도록 수정정
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
76
77
78
79
80
81
82
#include <iostream>
#include <vector>

using namespace std;

vector<int> arr;
vector<long long> tree;

long long Sum(int cur, int left, int right, int targetL, int targetR){
    // 포함 조건
    if(targetL <= left && right <= targetR){
        return tree[cur];
    }

    // 미포함 조건으로 구분
    if (right < targetL || targetR < left) {
        return 0;
    }


    int mid = (left+right) / 2;
    return Sum(cur * 2, left, mid, targetL, targetR) + Sum(cur * 2 + 1, mid+1, right, targetL, targetR);

}

void Modify(int cur, int left, int right, int index, long long diff){
    if(index == left && index == right){
        tree[cur] += diff;
        return;
    }

    // 범위를 벗어났을 때
    if(right < index || left > index){
        return;
    }

    if(left <= index && index <= right){
        int mid = (left+right) / 2;
        tree[cur] += diff;
        Modify(cur * 2, left, mid, index, diff);
        Modify(cur * 2 + 1, mid+1, right, index, diff);
    }

    return;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int n, m;
    cin >> n >> m;

    tree = vector<long long>(4*n+1, 0);
    arr = vector<int>(n+1, 0);

    for(int i = 0; i < m; i++){
        int oper, a;
        cin >> oper >> a;
        if(oper == 0){
            // Sum
            int b;
            cin >> b;

            if (a > b) swap(a, b);

            cout << Sum(1, 1, n, a, b) << '\n';
        }else if(oper == 1){
            // Modify
            long long k;
            cin >> k;

            long long diff = k - arr[a];
            arr[a] = k;
            Modify(1, 1, n, a, diff);
        }
    }
    
    return 0;
}

회고

  • sum을 구현할 때도 포함 구간, 미포함 구간으로 나눠서 처리하는 걸로 생각하기
This post is licensed under CC BY 4.0 by the author.