-
Notifications
You must be signed in to change notification settings - Fork 22
/
find all four sum numbers
83 lines (75 loc) · 2.47 KB
/
find all four sum numbers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Given an array A of size N, find all combination of four elements in the array whose sum is equal to a given value K. For example, if the
given array is {10, 2, 3, 4, 5, 9, 7, 8} and K = 23, one of the quadruple is “3 5 7 8” (3 + 5 + 7 + 8 = 23).
The output should contain only unique quadrples For example, if input array is {1, 1, 1, 1, 1, 1} and K = 4, then output should be only one
quadrple {1, 1, 1, 1}
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains two lines. The
first line of input contains two integers N and K. Then in the next line are N space separated values of the array.
Output:
For each test case in a new line print all the quadruples present in the array separated by space which sums up to value of K. Each quadruple
is unique which are separated by a delimeter "$" and are in increasing order.
Constraints:
1 <= T <= 100
1 <= N <= 100
-1000 <= K <= 1000
-100 <= A[] <= 100
Example:
Input:
2
5 3
0 0 2 1 1
7 23
10 2 3 4 5 7 8
Output:
0 0 1 2 $
2 3 8 10 $2 4 7 10 $3 5 7 8 $
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
int t; cin>>t; while(t--){
int n,k; cin>>n>>k;
int a[n]; for(int i=0; i<n; i++) cin>>a[i];
sort(a,a+n);
vector< vector<int> > res;
for(int i=0; i<n; i++ ){
for(int j=i+1; j<n; j++){
int left=j+1;
int right=n-1;
while(left<right){
int s=a[i]+a[j]+a[left]+a[right];
if(s==k){
vector<int> v;
v.push_back(a[i]);
v.push_back(a[j]);
v.push_back(a[left]);
v.push_back(a[right]);
res.push_back(v);
}
if(s>k){
do{--right;}
while(a[right+1] == a[right] && right>left);
}
else{
do{++left;}
while(a[left] == a[left-1] && right>left);
}
}
while(j+1<n && a[j] == a[j+1]) ++j;
}
while(i+1<n && a[i]==a[i+1]) ++i;
}
// sort(res.begin(), res.end());
if(res.size()==0) cout<<-1<<endl;
else{
for(int i=0; i<res.size(); i++){
for(int j=0; j<res[i].size(); j++ ){
cout<<res[i][j]<<" ";
}
cout<<"$";
}
cout<<endl;
}
}
}