Skip to content

Instantly share code, notes, and snippets.

@danielsaad
Created December 9, 2019 21:58
Show Gist options
  • Save danielsaad/5ed6463bca56ff8331ddfc271055e4aa to your computer and use it in GitHub Desktop.
Save danielsaad/5ed6463bca56ff8331ddfc271055e4aa to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
int n, k;
vector<int> v;
vector<vector<int>> boxes;
bool backtrack(int ik, int sum, int d_sum, int taken) {
if (ik == k && sum == 0) {
return true;
} else if (ik < k && sum == d_sum) {
return backtrack(ik + 1, 0, d_sum, taken);
} else if (sum > d_sum) {
return false;
}
for (int i = 0; i < n; i++) {
if ((taken >> i & 1) == 0) {
taken ^= 1 << i;
boxes[ik].push_back(v[i]);
bool rv = backtrack(ik, sum + v[i], d_sum, taken);
if (rv)
return true;
boxes[ik].pop_back();
taken ^= 1 << i;
}
}
return false;
}
void solve() {
int sum = 0;
for (auto e : v) {
sum += e;
}
if (sum % k != 0) {
cout << "impossivel" << endl;
} else if (backtrack(0, 0, sum / k, 0)) {
for (int i = 0; i < k; i++) {
cout << boxes[i].size() << ' ';
for (int j = 0; j < (int) boxes[i].size(); j++) {
cout << boxes[i][j];
cout << (j < (int) boxes[i].size() - 1 ? ' ' : '\n');
}
}
} else {
cout << "impossivel" << endl;
}
}
int main() {
cin >> n >> k;
v.resize(n);
boxes.resize(k);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
solve();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment