[백준 17408] 수열과 쿼리 24

문제 링크

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

풀이

$A_i + A_j$의 최댓값은 구간 안의 최댓값 두개를 더하는 것과 같습니다. 구간안의 최댓값 2개를 pair<int, int>로 관리하는 세그먼트 트리를 이용해 쿼리를 처리하면 최종 시간복잡도는 $O(M \log N)$입니다. 자세한 구현은 코드를 참고해주세요.

전체 코드

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
#include<bits/stdc++.h>
using namespace std;
using ll = long long;

#define mid ((l + r) >> 1)

int n, q;
pair<int, int> t[400400];

pair<int, int> merge(pair<int, int> a, pair<int, int> b){
    if(a < b) swap(a, b);

    if(a.second < b.first) a.second = b.first;
    else if(a.second < b.second) a.second = b.second;

    return a;
}

void update(int id, int val, int node = 1, int l = 1, int r = n){
    if(id < l || r < id) return;
    if(l == r){
        t[node] = {val, -1e9};
        return;
    }
    update(id, val, node*2, l, mid), update(id, val, node*2+1, mid+1, r);
    t[node] = merge(t[node*2], t[node*2+1]);
}

pair<int, int> find(int nl, int nr, int node = 1, int l = 1, int r = n){
    if(r < nl || nr < l) return {-1e9, -1e9};
    if(nl <= l && r <= nr) return t[node];
    return merge(find(nl, nr, node*2, l, mid), find(nl, nr, node*2+1, mid+1, r));
}

int sum(pair<int, int> p){
    return p.first + p.second;
}

int main(){
    ios_base::sync_with_stdio(0);cin.tie(0);
    cin >> n;
    for(int i=1;i<=n;i++){
        int a; cin >> a;
        update(i, a);
    }

    cin >> q;
    while(q--){
        int a, b, c; cin >> a >> b >> c;
        if(a == 1) update(b, c);
        else cout << sum(find(b, c)) << "\n";
    }
}