fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void solve(int arr[], int n, int target) {
  5.  
  6. // sort the array
  7. sort(arr, arr+n);
  8.  
  9. // for counting the total no. of triplets
  10. int count = 0;
  11.  
  12. // consider i for the first element
  13. for(int i = 0; i < n-2; i++) {
  14.  
  15. if(arr[i] > target) break;
  16.  
  17. // remaining sum
  18. int sum = target - arr[i];
  19.  
  20. // find a pair with given sum from arr[i+1, n-1];
  21. int j = i+1, k = n-1;
  22. while(j < k) {
  23.  
  24. int temp = arr[j] + arr[k];
  25.  
  26. if(temp == sum) {
  27. cout << arr[i] << " " << arr[j] << " " << arr[k] << endl;
  28. return;
  29. }
  30. else if(temp < sum) {
  31. j++;
  32. }
  33. else {
  34. k--;
  35. }
  36. }
  37. }
  38.  
  39. cout << "-1" << endl;
  40. }
  41.  
  42. int main() {
  43.  
  44. int t;
  45. cin >> t;
  46.  
  47. while(t--) {
  48.  
  49. int n;
  50. cin >> n;
  51.  
  52. int arr[n];
  53. for(int i = 0; i < n; i++)
  54. cin >> arr[i];
  55.  
  56. int target;
  57. cin >> target;
  58.  
  59. solve(arr, n, target);
  60. }
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 0s 5552KB
stdin
2 6 1 4 45 6 10 8 22 6 12 3 4 1 6 9 24
stdout
4 8 10
3 9 12