fork download
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <set>
  7. #define lli long long int
  8. using namespace std;
  9.  
  10. int main() {
  11. int t;
  12. cin>>t;
  13. while(t--){
  14. int n,k;
  15. cin>>n>>k;
  16. lli a[n];
  17. vector<lli> left,unique;
  18. for(int i=0;i<n;i++) cin>>a[i];
  19. sort(a,a+n);
  20. lli current=a[0];
  21. //left stores only the repettive elements
  22. //eg: if a = [1,2,2,3,3,3,4,4] then left = [2,3,3,4]
  23. for(int i=1;i<n;i++){
  24. if(a[i]==current) left.push_back(a[i]);
  25. else current = a[i];
  26. }
  27. //set 's' stores unique elemts from array 'a'
  28. set<lli> s;
  29. for(int i=0;i<n;i++) s.insert(a[i]);
  30. unique.assign(s.begin(),s.end());
  31. //checks if value of 'k' is <= number of unique elements
  32. if(unique.size()>=k){
  33. cout<<"-1"<<endl;
  34. continue;
  35. }
  36. //num stores the count of remaining elements we need to find other than unique
  37. int num = k - unique.size();
  38. //left already sorted, taking first 'num' elements from 'left' to make up k values
  39. for(int i=0;i<num;i++){
  40. unique.push_back(left[i]);
  41. }
  42. //unique is no more unique, but contains all the elements choosen to give
  43. sort(unique.begin(),unique.end());
  44. //rest of the procedure tries to find the best two sides if possible
  45. lli x1,x2;
  46. x1=unique[unique.size()-1];
  47. bool flag=false,first_time=true,yes=false;
  48. for(int i=unique.size()-2;i>=0;i--){
  49. if(flag){
  50. if(first_time){
  51. x2=unique[i];
  52. first_time=false;
  53. }
  54. else{
  55. if(unique[i]==x2) {yes=true;break;}
  56. else x2=unique[i];
  57. }
  58. }
  59. else{
  60. if(unique[i]!=x1) x1=unique[i];
  61. else {flag=true;first_time=true;}
  62. }
  63. }
  64. if(yes){
  65. lli prod = x1*x2;
  66. cout<<prod<<endl;
  67. }
  68. else{
  69. cout<<"-1"<<endl;
  70. }
  71.  
  72. }
  73. return 0;
  74. }
Time limit exceeded #stdin #stdout 5s 4388KB
stdin
Standard input is empty
stdout
Standard output is empty