fork download
  1.  
  2.  
  3. #include <iostream>
  4. #include <vector>
  5. #include <unordered_map>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. void Ktop(int *arr, int n, int k) {
  10. vector<int> top(k+1);
  11. unordered_map<int, int> freq;
  12. for(int m=0;m<n;m++) {
  13. freq[arr[m]]++;
  14. top[k] = arr[m];
  15. auto it = find(top.begin(), top.end()-1, arr[m]);
  16. for(int i=distance(top.begin(), it)-1;i>=0;i--) {
  17. if(freq[top[i]]<freq[top[i+1]]) {
  18. swap(top[i], top[i+1]);
  19. } else if(freq[top[i]]==freq[top[i+1]] and top[i]>top[i+1]) {
  20. swap(top[i], top[i+1]);
  21. } else {
  22. break;
  23. }
  24. }
  25. for (int i = 0; i < k && top[i] != 0; ++i)
  26. cout << top[i] << ' ';
  27. }
  28.  
  29. cout<<endl;
  30. }
  31.  
  32. int main(int argc, char const *argv[])
  33. {
  34. /* code */
  35. int t;
  36. cin>>t;
  37. while(t--) {
  38. int n, k;
  39. cin>>n>>k;
  40. int *arr = new int[n];
  41. for(int i=0;i<n;i++) {
  42. cin>>arr[i];
  43. }
  44. Ktop(arr, n, k);
  45. delete [] arr;
  46. }
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0.01s 5516KB
stdin
Standard input is empty
stdout
Standard output is empty