Question Name:Find all four sum numbers

#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <climits>
#include <iomanip>
#include <unordered_map>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include<iostream>
using namespace std;
#define ll long long


void fnc(vector<int>v,int k)
{ int fg=0;    
  sort(v.begin(),v.end());
  set<vector<int>>st;
  
  for(int a=0;a<v.size();a++)
  {
      for(int b=a+1;b<v.size();b++)
      {
        int sum=v[a]+v[b];
        for(int i=b+1,j=v.size()-1;i<j && sum<=k;)
        {
            if(sum+v[i]+v[j]==k) 
            {fg=1;
            vector<int> t={v[a],v[b],v[i],v[j]};
            if(st.find(t)==st.end())    {cout<<v[a]<<" "<<v[b]<<" "<<v[i]<<" "<<v[j]<<" $";}
            st.insert(t); i++;j--;    
            }
            else if(sum+v[i]+v[j]<k) {i++;}
            else j--;
        }
      }
  }
  if(fg==0) cout<<"-1";
}

int main()
{int t,m,k;
 //string s;
 
 cin>>t;
 while(t--)
 {
  cin>>m>>k;
  //cin>>s;
  vector<int>v(m);
  for(int i=0;i<m;i++) cin>>v[i];
  //cout<<fnc(v)<<endl; 
  fnc(v,k);
  cout<<endl;
}

	return 0;
}

Problem Description

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).

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

  • Test Case 1

    Input (stdin)

    2
    5 3
    0 0 2 1 1 
    7 23
    10 2 3 4 5 7 8
    

    Expected Output

    0 0 1 2 $
    2 3 8 10 $2 4 7 10 $3 5 7 8 $
  • Test Case 2

    Input (stdin)

    1
    5 3
    0 0 2 1 1
    

    Expected Output

    0 0 1 2 $
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO