Skip to content

Instantly share code, notes, and snippets.

@marat-turaev
Created December 17, 2013 19:30
Show Gist options
  • Save marat-turaev/8011126 to your computer and use it in GitHub Desktop.
Save marat-turaev/8011126 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstring>
#include <stack>
#define mem(a,v) memset(a,v,sizeof(a))
int w[100], d[100001], selected_card[100001];
int main() {
int weight, N;
std::cin >> weight >> N;
int total = 0;
for (int i = 0; i < N; ++i) {
std::cin >> w[i];
total += w[i];
}
weight = total - weight;
mem(d, 0);
mem(selected_card, 0);
d[0] = 1;
selected_card[0] = -1;
for (int i = 0; i < N; ++i) {
for (int j = weight; j >= w[i]; --j) {
if (d[j - w[i]] != 0) {
d[j] += d[j - w[i]];
if (selected_card[j] == 0) selected_card[j] = i + 1;
}
}
}
if (d[weight] > 1) {
std::cout << -1;
return 0;
}
if (d[weight] == 0) {
std::cout << 0;
return 0;
}
std::stack<int> res;
while (weight != 0) {
res.push(selected_card[weight]);
weight -= w[selected_card[weight] - 1];
}
while (!res.empty()) {
int cur = res.top();
res.pop();
std::cout << cur << " ";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment