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
83
84
85
86
87
#include <iostream>
#include <set>

using namespace std;

int main(){
    int n;
    
    cin >> n;

    multiset<long long> sprats;

    long long w;

    for (int i = 0; i < n; ++i){
        cin >> w;
        sprats.insert(w);
    }

    int q;

    cin >> q;

    for (int i = 0; i < q; ++i){
        int type;

        cin >> type;

        if (type == 1){
            long long s, k;

            cin >> s >> k;

            if (s >= k){
                cout << 0 << endl;
                continue;
            }

            multiset<long long> spratsTmp(sprats);

            multiset<long long>::iterator firstInaccessible = spratsTmp.lower_bound(s);

            if (firstInaccessible == spratsTmp.begin()){
                cout << -1 << endl;
                continue;
            }

            long long eatenCount = 0;

            multiset<long long>::iterator currentToEat = prev(firstInaccessible);

            for (;;){
                s += *currentToEat;
                ++eatenCount;

                if (s >= k){
                    cout << eatenCount << endl;
                    break;
                }

                currentToEat = spratsTmp.erase(currentToEat);
                // firstInaccessible = currentToEat;// repair broken iterator

                while (firstInaccessible != spratsTmp.end() && s > *firstInaccessible){
                    ++firstInaccessible;
                }

                if (firstInaccessible == spratsTmp.begin()){
                    cout << -1 << endl;
                    break;
                }

                currentToEat = prev(firstInaccessible);
            }
        }
        else if (type == 2){
            cin >> w;
            sprats.insert(w);
        }
        else{// type == 3
            cin >> w;
            sprats.erase(w);
        }
    }   

    return 0;
}