Skip to content

Instantly share code, notes, and snippets.

@asi1024
Created October 11, 2016 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asi1024/a46bc9dd85239b3f3e8835b142fbee4c to your computer and use it in GitHub Desktop.
Save asi1024/a46bc9dd85239b3f3e8835b142fbee4c to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(),(x).end()
using namespace std;
int N, M;
int s[16], d[128];
int memo[1<<15][128];
int dp(int bit, int day, int sum) {
if (day == -1) return 0;
if (memo[bit][day] != -1) return memo[bit][day];
int res = dp(bit, day - 1, sum) + abs(sum - d[day]);
REP(i,N) {
if ((bit >> i) & 1)
res = min(res, dp(bit - (1 << i), day, sum - s[i]));
}
return memo[bit][day] = res;
}
int main() {
while (cin >> N >> M, N) {
REP(i,N) cin >> s[i];
REP(i,M) cin >> d[i];
sort(d, d + M);
memset(memo, -1, sizeof(memo));
int res = dp((1 << N) - 1, M - 1, accumulate(s, s + N, 0));
cout << res << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment