Untitled

 avatar
unknown
plain_text
a year ago
1.8 kB
5
Indexable
#include <bits/stdc++.h>
using namespace std;

#define pfi(a) printf("%d", a);
#define pfl(a) printf("%lld", a);
#define pfin(a) printf("%d\n", a);
#define pfln(a) printf("%lld\n", a);
#define pfis(a) printf("%d ", a);
#define pfls(a) printf("%lld ", a);
#define sfi(a) scanf("%d", &a);
#define sfl(a) scanf("%lld", &a);
#define fast                        \
  ios_base::sync_with_stdio(false); \
  cin.tie(NULL);                    \
  cout.tie(NULL)
#define f(i, a, b) for (int i = a; i < b; i++)
#define pb(a) push_back(a);
#define mp(a, b) make_pair(a, b)
#define ll long long
#define F first
#define S second

priority_queue<int, vector<int>, greater<int> > minheap;
priority_queue<int, vector<int> > maxheap;

void insert(int x) {
  if (minheap.size() == maxheap.size()) {
    if (maxheap.size() == 0) {
      maxheap.push(x);
      return;
    }
    if (x < maxheap.top()) {
      maxheap.push(x);
    } else {
      minheap.push(x);
    }

  }

  else {
    if (maxheap.size() > minheap.size()) {
      if (x >= maxheap.top()) {
        minheap.push(x);
      } else {
        int temp = maxheap.top();
        maxheap.pop();
        maxheap.push(x);
        minheap.push(temp);
      }
    }

    else {
      if (x <= minheap.top()) {
        maxheap.push(x);
      } else {
        int temp = minheap.top();
        minheap.pop();
        minheap.push(x);
        maxheap.push(temp);
      }
    }
  }
}

double findmedian() {
  if (maxheap.size() == minheap.size()) {
    return (maxheap.top() + minheap.top()) / 2;
  } else {
    if (maxheap.size() > minheap.size()) {
      return maxheap.top();
    } else {
      return minheap.top();
    }
  }
}

int main() {
  insert(10);
  insert(1);
  findmedian();
  insert(2);
  findmedian();
  insert(3);
  insert(11);
  findmedian();
  return 0;
}
Editor is loading...
Leave a Comment