#include #include using namespace std; // Find out how unfair a given divy of the loot among all of the people is. // The unfairness is the largest difference: the diff between min and max int unfair(const vector& people) { int min = people[0]; int max = people[0]; for (unsigned int i = 1; i < people.size(); ++i) { if (min > people[i]) min = people[i]; if (max < people[i]) max = people[i]; } return max - min; } // Do the divy: sort coins starting with coins[ind] such that the // value of each coin is given to one of the people, and // the total values are as close to even as possible. int divy(vector coins, int ind, vector people) { // If we've given out all the coins, we're done. if (ind == (int)coins.size()) return unfair(people); // Loop through all the people to see who had best get this coin for (unsigned int i = 0; i < people.size(); i++) { people[i] += coins[ind]; int temp = divy(coins, ind + 1, people); if ((i == 0) or temp < best) best = temp; people[i] -= coins[ind]; } // Return the best amount return best; } int main() { // How many coins are there? int n; while (cin >> n) { // Read in the value of each coin vector coins; coins.resize(n); for (int i = 0; i < n; i++) { cin >> coins[i]; } // How many people are there? int k; cin >> k; vector people; people.resize(k); // Print out the result cout << divy(coins, 0, people) << endl; } }