본문 바로가기

알고리즘 문제풀이

House Prices Going Up [백준 25778]

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

 

무엇이 틀린지 몰라 gpt에 물어보니 long long을 써야함을 알게됨 

#include <iostream>
#include <vector>

using namespace std;

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

long long init(int idx, int s, int e) {
    if (s == e) {
        tree[idx] = arr[s];
        return tree[idx];
    }
    int mid = s + (e - s) / 2;
    tree[idx] = init(idx * 2, s, mid) + init(idx * 2 + 1, mid + 1, e);
    return tree[idx];
}

void update(int idx, int s, int e, int p, long long val) {
    if (p < s || p > e) {
        return;
    }
    if (s == e) {
        tree[idx] += val; 
        return;
    }
    int mid = s + (e - s) / 2;
    update(idx * 2, s, mid, p, val);      
    update(idx * 2 + 1, mid + 1, e, p, val); 

    tree[idx] = tree[idx * 2] + tree[idx * 2 + 1];
}

long long find(int idx, int s, int e, int l, int r) {
    if (e < l || r < s) {
        return 0LL; // Return 0 as a long long value
    }
    if (l <= s && e <= r) {
        return tree[idx]; // Return the pre-calculated sum for this node
    }
    int mid = s + (e - s) / 2;
    return find(idx * 2, s, mid, l, r) + find(idx * 2 + 1, mid + 1, e, l, r);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n;
    arr.resize(n + 1);
    tree.resize(4 * n + 1);

    for (int i = 1; i <= n; i++) {
        cin >> arr[i];
    }

    init(1, 1, n); // Start from root node index 1, range [1, n]

    int k; // Read the number of transactions
    cin >> k;
    for (int i = 0; i < k; i++) {
        char type;    // Transaction type ('R' or 'U')
        int param1;  // House number (index) or start range index (fits in int)
        cin >> type >> param1;

        if (type == 'R') { // Retrieve transaction
            int param2; // End range index (fits in int)
            cin >> param2;
            cout << find(1, 1, n, param1, param2) << '\n';
        } else { // Update transaction (type == 'U')
            long long param2; // Price increase value (MUST be long long)
            cin >> param2;
            update(1, 1, n, param1, param2);
        }
    }

    return 0;
}

'알고리즘 문제풀이' 카테고리의 다른 글

친구비 [백준 16562]  (0) 2025.04.04
게임 [백준 1072]  (0) 2025.04.01
풍선 맞추기 [백준 11509]  (0) 2025.03.13
연료 채우기 [백준 1826]  (0) 2025.03.11
파일 합치기3 [백준 13975]  (0) 2025.03.09