fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main() {
  4. priority_queue<pair <int, string>, vector< pair <int, string> >, greater< pair <int, string> > > pq;
  5. int n, k;
  6. cin >> n >> k;
  7. map<string, int> m;
  8. for(int i = 0; i < n; i++){
  9. //int x;
  10. string x;
  11. cin >> x;
  12. if(m.find(x) != m.end()){
  13. m[x] = m[x] + 1;
  14. }
  15. else{
  16. m[x] = 1;
  17. }
  18. }
  19. int i = 0;
  20. for(auto it = m.begin(); it != m.end(); it++){
  21. string s = it -> first;
  22. int x = it -> second;
  23. if(i < k){
  24. pq.push(make_pair(x, s));
  25. }
  26. else{
  27. pair <int, string> p = pq.top();
  28. pq.pop();
  29. int x1 = p.first;
  30. string s1 = p.second;
  31. if(x1 > x){
  32. x = x1;
  33. s = s1;
  34. }
  35. else if(x1 == x and s.compare(s1) > 0){
  36. x = x1;
  37. s = s1;
  38. }
  39. pq.push(make_pair(x, s));
  40. }
  41. i++;
  42. }
  43. stack<string> s;
  44. while(!pq.empty()){
  45. pair <int, string> p = pq.top();
  46. pq.pop();
  47. int x1 = p.first;
  48. string s1 = p.second;
  49. s.push(s1);
  50. //cout << s1 << " ";
  51. }
  52. while(!s.empty()){
  53. string s1 = s.top();
  54. cout << s1 << " ";
  55. s.pop();
  56. }
  57. return 0;
  58. }
Success #stdin #stdout 0s 4404KB
stdin
Standard input is empty
stdout
Standard output is empty