fork(1) download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. int main() {
  7. int n; // size of array b
  8. cin >> n;
  9.  
  10. int b[n]; // array b
  11. for (int i = 0; i < n; i++) {
  12. cin >> b[i];
  13. }
  14.  
  15. int k; // value of k
  16. cin >> k;
  17.  
  18. priority_queue<int> q;
  19.  
  20. for(int i = 0;i < n;i++)
  21. {
  22. if(q.empty() || q.top() <= b[i])
  23. q.push(b[i]);
  24. else if(b[i] < q.top())
  25. {
  26. while(!q.empty() && q.top() > b[i])
  27. {
  28. q.pop();
  29. }
  30. q.push(b[i]);
  31. }
  32. if(q.size() > k)
  33. q.pop();
  34. // cout << q.top() << endl;
  35. }
  36. vector<int> ans;
  37. while(!q.empty())
  38. {
  39. ans.insert(ans.begin() + 0, q.top());
  40. q.pop();
  41. }
  42. for(auto i : ans)
  43. cout << i << " ";
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 5300KB
stdin
4
8 1 3 2
3
stdout
1 2