Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Author : Dipu Kumar Mohanto (Dip)
- * CSE, BRUR.
- *
- * Problem : Find the Running Median
- * Algorithm : Maximum Heap & Minimum Heap (STL)
- * Compleixty :
- * Category : find median, sorting
- *
- * Source : Hacker Rank
- *
- * Verdict : Accepted
- *
- * Date :
- * E-mail : dipukumarmohanto1@gmail.com
- ***/
- #include <bits/stdc++.h>
- using namespace std;
- priority_queue <int, vector <int>, less <int> > maxHeap;
- priority_queue <int, vector <int>, greater <int> > minHeap;
- int main()
- {
- int n;
- cin >> n;
- int fnum, snum;
- double median;
- for (int f=0; f<2; f++)
- {
- int num;
- cin >> num;
- if (f==0)
- {
- fnum = num;
- median = (double)num;
- printf("%.1lf\n", median);
- // continue;
- }
- else if (f==1)
- {
- snum = num;
- median = ((double)num + (double)fnum) / 2.0;
- printf("%.1lf\n", median);
- // continue;
- }
- }
- int maxNum = max(fnum, snum);
- int minNum = min(fnum, snum);
- maxHeap.push(minNum);
- minHeap.push(maxNum);
- for (int f=2; f<n; f++)
- {
- int num;
- cin >> num;
- if (maxHeap.top() > num)
- {
- maxHeap.push(num);
- }
- else
- {
- minHeap.push(num);
- }
- int minHeapLen = minHeap.size();
- int maxHeapLen = maxHeap.size();
- if (minHeapLen > maxHeapLen)
- {
- int m = minHeap.top();
- minHeap.pop();
- maxHeap.push(m);
- }
- else if (maxHeapLen > minHeapLen)
- {
- int m = maxHeap.top();
- maxHeap.pop();
- minHeap.push(m);
- }
- minHeapLen = minHeap.size();
- maxHeapLen = maxHeap.size();
- //cout << minHeapLen << " " << maxHeapLen << endl;
- // ans
- if (minHeapLen > maxHeapLen)
- {
- median = (double)minHeap.top();
- }
- else if (maxHeapLen > minHeapLen)
- {
- median = (double)maxHeap.top();
- }
- else if (minHeapLen == maxHeapLen)
- {
- double num1 = (double)minHeap.top();
- double num2 = (double)maxHeap.top();
- median = (num1 + num2) / 2.0;
- }
- printf("%.1lf\n", median);
- }
- return 0;
- }
- /**************************************
- Input:
- 6
- 12
- 4
- 5
- 3
- 8
- 7
- Output:
- 12.0
- 8.0
- 5.0
- 4.5
- 5.0
- 6.0
- Input:
- 2
- 5
- 3
- Output:
- 2.0
- 3.5
- 3.0
- ***********************************************************/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement