#include <bits/stdc++.h>
using namespace std;
// Function that tries every possible solution by calling
// itself recursively
void TOWUtil(const vector<int>& arr, vector<bool>& curr,
int sel, vector<bool>& resSel, int& minDiff,
int totalSum, int currSum, int pos) {
int n = arr.size();
// Check whether it is going out of bounds
if (pos == n)
return;
// Check that the number of elements left are not
// less than the number of elements required to
// form the solution
if ((n / 2 - sel) > (n - pos))
return;
// Consider the case when current element is not included
TOWUtil(arr, curr, sel, resSel, minDiff, totalSum, currSum, pos + 1);
// Add the current element to the solution
sel++;
currSum += arr[pos];
curr[pos] = true;
// Check if a solution is formed
if (sel == n / 2) {
// Check if this solution is better than the best so far
int diff = abs(totalSum / 2 - currSum);
if (diff < minDiff) {
minDiff = diff;
resSel = curr;
}
}
else {
// Consider the case where current element is included
TOWUtil(arr, curr, sel, resSel, minDiff, totalSum, currSum, pos + 1);
}
// Remove current element before returning to the caller
curr[pos] = false;
}
// Function that returns the two subsets
pair<vector<int>, vector<int>> tugOfWar(const vector<int>& arr) {
int n = arr.size();
// Boolean array that contains inclusion/exclusion of an element
vector<bool> curr(n, false);
// Final solution mask
vector<bool> resSel(n, false);
int minDiff = INT_MAX;
// Total sum of all elements
int totalSum = accumulate(arr.begin(), arr.end(), 0);
// Recursive solution
TOWUtil(arr, curr, 0, resSel, minDiff, totalSum, 0, 0);
// Prepare the two subsets
vector<int> res1, res2;
for (int i = 0; i < n; ++i) {
if (resSel[i])
res1.push_back(arr[i]);
else
res2.push_back(arr[i]);
}
return {res1, res2};
}
// Driver program to test above functions
int main() {
vector<int> arr = {23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4};
// Get the two subsets
pair<vector<int>, vector<int>> res = tugOfWar(arr);
// Print the subsets
cout << "The first subset is: ";
for (int x : res.first)
cout << x << " ";
cout << "\nThe second subset is: ";
for (int x : res.second)
cout << x << " ";
return 0;
}