Last active
September 13, 2015 16:41
-
-
Save Acarus/7ef2a7d7e6c7b9ed1016 to your computer and use it in GitHub Desktop.
Divide set into two subset with minimum sum difference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
typedef unsigned long long ull; | |
int main(void) { | |
ios::sync_with_stdio(false); | |
int n; | |
cin >> n; | |
vector<long long> m(n); | |
for(int i = 0; i < n; i++) { | |
cin >> m[i]; | |
} | |
pair< vector<long long>, int> ans; | |
sort(m.begin(), m.end()); | |
long long prev_sub = LONG_LONG_MAX; | |
long long totalSum = accumulate(m.begin(), m.end(), 0); | |
while(true) { | |
for(int i = 1; i < m.size(); i++) { | |
long long partialSum = accumulate(m.begin(), m.begin() + i, 0); | |
if(abs(totalSum - partialSum - partialSum) < prev_sub) { | |
prev_sub = abs(totalSum - partialSum - partialSum); | |
ans = make_pair(m, i); | |
} | |
} | |
if(!next_permutation(m.begin(), m.end())) | |
break; | |
} | |
cout << "A = "; | |
for(int i = 0; i < ans.second; i++) | |
cout << ans.first[i] << " "; | |
cout << endl; | |
cout << "B = "; | |
for(int i = ans.second; i < ans.first.size(); i++) | |
cout << ans.first[i] << " "; | |
cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment