L3-002 特殊堆疊
阿新 • • 發佈:2022-04-19
#include <bits/stdc++.h> using namespace std; const int N = 1E5 + 10; int tr[N]; stack<int> stk; int lowbit(int x) { return x & -x; } void add(int x, int d) { for (int i = x; i < N; i += lowbit(i)) { tr[i] += d; } } int query(int x) { int res = 0; for (int i = x; i; i -= lowbit(i)) { res += tr[i]; } return res; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; for (int i = 0; i < n; i++) { string op; cin >> op; if (op == "Pop") { //cout << op << " "; if (stk.empty()) { cout << "Invalid" << "\n"; } else { int x = stk.top(); stk.pop(); cout << x << "\n"; add(x, -1); } } else if (op == "PeekMedian") { //cout << "PeekMedian" << " "; if (stk.empty()) { cout << "Invalid" << "\n"; } else { int md = ((int)stk.size() + 1) / 2; int l = 0, r = 100000; while (l < r) { int mid = l + r >> 1; if (query(mid) >= md) r = mid; else l = mid + 1; } cout << l << "\n"; } } else { //cout << "Push" << " "; int x; cin >> x; stk.push(x); add(x, 1); } } return 0; }