1. 程式人生 > >洛谷 [TJOI2010]中位數

洛谷 [TJOI2010]中位數

題目連結

題解

比較水。。

常見套路,維護兩個堆

Code

#include<bits/stdc++.h>
#define LL long long
#define RG register
using namespace std;

inline int gi() {
    int f = 1, s = 0;
    char c = getchar();
    while (c != '-' && (c < '0' || c > '9')) c = getchar();
    if (c == '-') f = -1, c = getchar();
    while (c >= '0' && c <= '9') s = s*10+c-'0', c = getchar();
    return f == 1 ? s : -s;
}

priority_queue<int> p;
priority_queue<int, vector<int>, greater<int> > q;
const int N = 100010;
int a[N];
char s[10];
int main() {
    int n = gi();
    for (int i = 1; i <= n; i++) a[i] = gi();
    sort(a+1, a+1+n);
    int t = gi(), s1 = (n+1)/2, s2 = n-s1;
    for (int i = 1; i <= s1; i++)
        p.push(a[i]);
    for (int i = s1+1; i <= n; i++)
        q.push(a[i]);
    while (t--) {
        cin >> s;
        if (s[0] == 'a') {
            q.push(gi());
            s2++;
            if (q.top() < p.top()) {
                int tmp = q.top(); q.pop();
                q.push(p.top()); p.pop();
                p.push(tmp);
            }
            if (s1 < s2) {
                s2--;
                s1++;
                p.push(q.top());
                q.pop();
            }
        }
        else printf("%d\n", p.top());
    }
    return 0;
}