40分,各位大佬帮忙看下

P1168 中位数

jh2023 @ 2024-08-02 12:09:55

我不知道为什么,好像输出答案的时候会多出几个,前面的应该是对的

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int n;
int nums[100005];
int cnt;
int c;
int get_abs(int, int);
priority_queue <int> q_max;
priority_queue <int, vector<int>, greater<int> > q_min;

int main() {
    cin >> n;
    int temp;
    for (int i = 1; i <= n; i++) {
        if (c == 2) {
            c = 0;
            while (get_abs(q_max.size(), q_min.size()) > 1) {
                if (q_max.size() > q_min.size()) {
                    q_min.push(q_max.top());
                    q_max.pop();
                } else {
                    q_max.push(q_min.top());
                    q_min.pop();
                }
            }
            if (q_max.size() > q_min.size()) {
                nums[++cnt] = q_max.top();
            } else {
                nums[++cnt] = q_min.top();
            }
            temp = nums[cnt];
        }
        int num;
        cin >> num;
        if (i == 1 || i == n) {
            nums[++cnt] = num;
        }
        if (i == 1) {
            temp = num;
            q_max.push(num);
            continue;
        }
        c++;
        if (num > temp) {
            q_min.push(num);
        } else {
            q_max.push(num);
        }
    }
    for (int i = 1; i <= cnt; i++) {
        cout << nums[i] << endl;
    }
    return 0;
}

int get_abs(int a, int b) {
    if (a > b) {
        return a - b;
    } else {
        return b - a;
    }
}

|