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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 `#include using namespace std; using lld = long long; const lld INF = 1e18; int MAXN; struct Query{ int type; lld a,b; }; struct SegmentTree{ vector tree; int base; SegmentTree(int base=(1<<20)): tree(2*base,0), base(base) {} void insert(int x, lld val){ x += base; tree[x] = val; while(x > 1){ x /= 2; tree[x] = tree[2*x] + tree[2*x+1]; } } lld query(int b, int e){ if(b > e) return 0; b += base, e += base; lld val = tree[b] + (b != e ? tree[e] : 0); while(b/2 != e/2){ if(b%2 == 0) val += tree[b+1]; if(e%2 == 1) val += tree[e-1]; b /= 2, e /= 2; } return val; } lld bin(int v, lld val){ while(v < base){ if(val >= tree[2*v+1]) v = 2*v+1; else val -= tree[2*v+1], v = 2*v; } return v-base; } }; SegmentTree sum; SegmentTree cnt; multiset > S; map M; void add(lld x){ int nr = M[x]++; sum.insert(nr,x); cnt.insert(nr,1); S.insert({x,nr}); } void remove(lld x){ int nr = --M[x]; sum.insert(nr,0); cnt.insert(nr,0); S.erase({x,nr}); } int bin(int b, int e, lld val){ val += sum.query(e+1,MAXN); return sum.bin(1,val); } int solve(lld x, lld y){ vector > stk; set >::iterator it; int res = 0; int pos; y--; it = S.lower_bound({x,-1}); pos = (it != S.end() ? it->second : MAXN); if(pos >= 1) stk.push_back({0,pos-1}); while(x <= y && !stk.empty()){ it = S.lower_bound({x,-1}); lld k = min((it != S.end() ? it->first : INF), y); while(!stk.empty() && x <= k){ int p = min(stk.back().second, bin(stk.back().first, stk.back().second, k-x+1)); res += cnt.query(p, stk.back().second); x += sum.query(p, stk.back().second); stk.back().second = p-1; if(stk.back().first > stk.back().second) stk.pop_back(); } int tmp = pos; it = S.lower_bound({x,-1}); pos = (it != S.end() ? it->second : MAXN); if(tmp <= pos-1) stk.push_back({tmp,pos-1}); } return (x <= y ? -1 : res); } int main(void){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector w(n+1); for(int i=1;i<=n;i++) cin >> w[i]; int q; cin >> q; vector t(q); for(auto& i : t){ cin >> i.type >> i.a; if(i.type == 1) cin >> i.b; } vector V; V.reserve(n+q); for(int i=1;i<=n;i++) V.push_back(w[i]); for(auto& i : t) if(i.type == 2) V.push_back(i.a); sort(V.begin(), V.end()); lld last = -1; for(int i=0;i