Advertisement
Guest User

Untitled

a guest
May 20th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <fstream>
  5.  
  6. using namespace std;
  7.  
  8. struct Median {
  9.     int value;
  10.     //int index;
  11. };
  12.  
  13. int main() {
  14.     ifstream fin ("input.txt");
  15.     ofstream fout ("output.txt");
  16.     int n;
  17.     fin >> n;
  18.     priority_queue<int> max_heap;
  19.     priority_queue<int, vector<int>, greater<int>> min_heap;
  20.  
  21.     int a;
  22.     Median median;
  23.     median.value = 0;
  24.  
  25.     for (int i = 0; i < n; i++)
  26.     {
  27.         fin >> a;
  28.         //choosing
  29.         if (a < median.value)
  30.         {
  31.             max_heap.push(a);
  32.         }
  33.         else
  34.         {
  35.             min_heap.push(a);
  36.         }
  37.  
  38.         //balancing
  39.         int abs_ = max_heap.size() - min_heap.size();
  40.         if (abs(abs_) > 1)
  41.         {
  42.             if (max_heap.size() > min_heap.size())
  43.             {
  44.                 int tmp = max_heap.top();
  45.                 max_heap.pop();
  46.                 min_heap.push(tmp);
  47.             } else
  48.             {
  49.                 int tmp = min_heap.top();
  50.                 min_heap.pop();
  51.                 max_heap.push(tmp);
  52.             }
  53.         }
  54.  
  55.         //output
  56.         if (max_heap.empty())
  57.         {
  58.             fout << min_heap.top() << ' ';
  59.             median.value = min_heap.top();
  60.         }
  61.         else if (min_heap.empty())
  62.         {
  63.             fout << max_heap.top() << ' ';
  64.             median.value = max_heap.top();
  65.         }
  66.         else if (min_heap.top() > max_heap.top())
  67.         {
  68.             fout << max_heap.top() << ' ';
  69.             median.value = min_heap.top();
  70.         }
  71.         else
  72.         {
  73.             fout << min_heap.top() << ' ';
  74.             median.value = max_heap.top();
  75.         }
  76.     }
  77.  
  78.     fin.close();
  79.     fout.close();
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement