Problem:
ぼくのかんがえたさいきょうのおふとん
あなたは新生活に備え，おふとんを
N
枚買った．
i
番目のおふとんは
s
i
のぬくもり供給力をもつ．
これから
M
日間の気温の予測から，
j
日目には
d
j
のぬくもり需要が予想される．
ぬくもりが足りなくても多すぎても快適さが損なわれるので，
j
日目に掛けているおふとんのぬくもり供給力の総和と
d
j
の差の絶対値を
j
日目の不快度と呼ぶことにする．
この
M
日分の不快度の合計ができるだけ少なくなるようにしたい．
ところで，あなたの部屋は残念ながらとても狭く，ベッドと押入れしかない．
そのため，ベッドにおふとんを 1 枚増やすには，そのとき押入れの一番上にあるおふとんをベッドの一番上に乗せるしかない．
逆に，ベッドのおふとんを 1 枚減らすには，そのときベッドの一番上にあるおふとんを押入れの一番上に置くしかない．
また，1 日に動かせるおふとんの枚数に制限は無いが，一度に 1 枚ずつしか動かすことができない．
さて，あなたはこれから買ってきたおふとんを押入れにしまう予定である．
このときに限り，おふとんを好きな順序で押入れにしまうことができる．
どのようにおふとんを押入れに収納し，その後，日々どのようにおふとんを出し入れすれば，快適に毎日を過ごせるだろうか．
M
日間の不快度の和を最小化するとき，その和の値を求めよ．
なお，一度も使われないおふとんがあってもよく，おふとんを一枚も使わない日があってもよい．
Input
入力は複数のデータセットからなる．
各データセットは以下の形式である．
N
M
s
1
s
2
...
s
N
d
1
d
2
...
d
M
データセットの 1 行目には，おふとんの枚数
N
と，気温が予測されている日数
M
を表す整数がスペース区切りで与えられる．
2 行目には
N
個の整数
s
1
, s
2
, ..., s
N
がスペース区切りで与えられ，
s
i
は
i
番のおふとんのぬくもり供給力を表す．
3 行目には
M
個の整数
d
1
, d
2
, ..., d
M
がスペース区切りで与えられ，
d
j
は
j
日目のぬくもり需要を表す．
これらの整数は，
1 ≤ N ≤ 15
,
1≤ M ≤ 100
,
1 ≤ s
i
, d
j
≤ 1,000,000
を満たす．
入力の終わりは
N = M = 0
のデータセットで表される．
このデータセットについて出力を行ってはならない．
Output
各データセットについて，
M
日間の不快度の和の最小値を 1 行に出力せよ．
Sample Input
1 1
5
6
1 1
5
2
1 1
20
5
4 1
2 4 5 9
8
4 3
3 5 2 1
10 4 7
5 5
2 2 2 2 2
1 3 5 7 9
2 5
2 5
2 5 2 5 2
0 0
Output for Sample Input
1
2
5
1
1
5
4
5 つ目のケースについては，上から 5, 2, 3, 1 と押入れに置き，1 日目は 3 枚取り出し |10 - (5 + 2 + 3)| = 0，2 日目は 2 枚しまい |4 - 5| = 1，3 日目は 1 枚取り出し |7 - (5+2)| = 0 で，合計 0 + 1 + 0 = 1 となる．

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
      
#define FOR(i,a,b) for( ll i = (a); i < (ll)(b); i++ )
#define REP(i,n) FOR(i,0,n)
#define YYS(x,arr) for(auto& x:arr)
#define ALL(x) (x).begin(),(x).end()
#define SORT(x) sort( (x).begin(),(x).end() )
#define REVERSE(x) reverse( (x).begin(),(x).end() )
#define UNIQUE(x) (x).erase( unique( ALL( (x) ) ) , (x).end() )
#define PW(x) (1LL<<(x))
#define SZ(x) ((ll)(x).size())
#define SHOW(x) cout << #x << " = " << x << endl
#define SHOWA(x,n) for( int yui = 0; yui < n; yui++ ){ cout << x[yui] << " "; } cout << endl

#define pb emplace_back
#define fi first
#define se second

using namespace std;

typedef long double ld;
typedef long long int ll;
typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<bool> vb;
typedef vector<ld> vd;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<vpl> gr;
typedef vector<vl> ml;
typedef vector<vd> md;
typedef vector<vi> mi;
     
const ll INF = (ll)1e9 + 10;
const ll INFLL = (ll)1e18 + 10;
const ld EPS = 1e-12;
const ll MOD = 1e9+7;
     
template<class T> T &chmin( T &a , const T &b ){ return a = min(a,b); }
template<class T> T &chmax( T &a , const T &b ){ return a = max(a,b); }
template<class T> inline T sq( T a ){ return a * a; }

ll in(){ long long int x; scanf( "%lld" , &x ); return x; }
char yuyushiki[1000010]; string stin(){ scanf( "%s" , yuyushiki ); return yuyushiki; }

// head

int n, m;

int a[15];
int b[110];

int w[PW(15)];

int dp[PW(15)][110];

int main(){

  while( 1 ){
    n = in();
    m = in();
    if( n == 0 && m == 0 ){
      break;
    }
    REP( i , n ){
      a[i] = in();
    }
    REP( i , m ){
      b[i] = in();
    }
    sort( b , b + m );
    REP( i , PW(n) ){
      w[i] = 0;
      REP( j , n ){
        if( i & PW(j) ){
          w[i] += a[j];
        }
      }
    }
    REP( i , PW(n) ){
      REP( j , m+1 ){
        dp[i][j] = INF;
      }
    }
    dp[0][0] = 0;
    REP( i , PW(n) ){
      REP( j , m+1 ){
        if( j < m ){
          chmin( dp[i][j+1] , dp[i][j] + abs( w[i] - b[j] ) );
        }
        REP( k , n ){
          chmin( dp[i|PW(k)][j] , dp[i][j] );
        }
      }
    }
    printf( "%d\n" , dp[PW(n)-1][m] );
  }

  return 0;
}
accuracy: 1
time_ms: 510
memory_kb: 17792
final_rank: 12

code_snippet: #include <bits/stdc++.h>
#include <unordered_map>
#include <stdlib.h>
using namespace std;
#define rep(i, a, n) for(ll i = a; i < n; i++)
#define rrep(i, a, n) for(ll i = a; i >= n; i--)
#define ll long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define all(x) (x).begin(), (x).end()
//constexpr ll MOD = 1000000007;
constexpr ll MOD = 998244353;
constexpr int IINF = 1001001001;
constexpr ll INF = 1LL<<60;
template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(b<a)a=b;}

int main(){
    while(true){
        int n, m; cin >> n >> m;
        if(n == 0) break;
        vector<int> s(n), d(m);
        rep(i, 0, n) cin >> s[i];
        vector<ll> sum(1<<n);
        rep(i, 0, 1<<n){
            rep(j, 0, n){
                if((i>>j)&1){
                    sum[i] += s[j];
                }
            }
        }

        rep(i, 0, m) cin >> d[i];
        sort(s.begin(), s.end());
        sort(d.begin(), d.end());
        vector<ll> dp(1<<n, IINF);
        dp[0] = 0;
        rep(i, 0, m){
            vector<ll> ndp(1<<n, INF);
            rep(j, 0, 1<<n){
                rep(k, 0, n){
                    if(!((j>>k)&1)){
                        chmin(dp[j+(1<<k)], dp[j]);
                    }
                }
            }
            rep(j, 0, 1<<n){
                chmin(ndp[j], dp[j]+abs(sum[j]-d[i]));
                // rep(k, 0, n){
                //     if(!((j>>k)&1)){
                //         chmin(ndp[j+(1<<k)], dp[j]+abs(sum[j+(1<<k)]-d[i]));
                //     }
                // }
            }
            swap(dp, ndp);
        }

        ll ans = INF;
        rep(i, 0, 1<<n) chmin(ans, dp[i]);
        cout << ans << endl;
    
    }




    return 0;
}
accuracy: 1
time_ms: 1510
memory_kb: 4224
final_rank: 15

code_snippet: #include <bits/stdc++.h>
#include <unordered_map>
#include <stdlib.h>
using namespace std;
#define rep(i, a, n) for(ll i = a; i < n; i++)
#define rrep(i, a, n) for(ll i = a; i >= n; i--)
#define ll long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define all(x) (x).begin(), (x).end()
//constexpr ll MOD = 1000000007;
constexpr ll MOD = 998244353;
constexpr int IINF = 1001001001;
constexpr ll INF = 1LL<<60;
template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(b<a)a=b;}


ll gcd(ll a, ll b){
    if(a%b == 0){
      return b;
    }else{
      return gcd(b, a%b);
    }
}

ll lcm(ll a, ll b){
    return a*b / gcd(a, b);
}

ll powMod(ll x, ll n) {
    if (n == 0) return 1 % MOD;
    ll val = powMod(x, n / 2);
    val *= val;
    val %= MOD;
    if (n % 2 == 1) val *= x;
    return val % MOD;
}

int main() {
    while(true){
        ll n, m; cin >> n >> m;
        if(n*m == 0) break;
        vector<ll> s(n), d(m);
        rep(i,0,n) cin >> s[i];
        rep(i,0,m) cin >> d[i];
        sort(all(s));
        sort(all(d));
        vector<ll> dp(1LL<<n,INF);
        vector<ll> sum(1LL<<n,0);
        rep(i,0,1LL<<n){
            rep(j,0,n) if(i>>j&1) sum[i] += s[j];
        }
        dp[0] = 0;
        rep(i,0,m){
            vector<ll> ndp(1LL<<n,INF);
            rep(bit,0,1LL<<n){
                rep(j,0,n){
                    if(bit>>j&1) continue;
                    chmin(dp[bit^(1LL<<j)], dp[bit]);
                }
            }
            rep(bit,0,1LL<<n){
                chmin(ndp[bit], dp[bit]+abs(d[i]-sum[bit]));
            }
            rep(bit,0,1LL<<n){
                rep(j,0,n){
                    if(bit>>j&1) continue;
                    chmin(ndp[bit^(1LL<<j)], ndp[bit]);
                }
            }
            swap(dp,ndp);
        }
        cout << dp[(1LL<<n)-1] << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 2900
memory_kb: 4224
final_rank: 18

code_snippet: #include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <set>
#include <unordered_set>
#include <map>
#include <iomanip>
#include <unordered_map>
#include <functional>
#include <atcoder/all>
using namespace std;
using namespace atcoder;
using pii = pair<int, int>;
using vi = vector<int>;
using vii = vector<pii>;
using ll = long long;
using pll = pair<ll, ll>;
using vl = vector<ll>;
using vll = vector<pll>;
using mint = modint998244353;
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

int main() {
    while(1) {
        ll n,m;
        cin >> n >> m;
        if(n==0 && m==0) break;
        vl s(n),t(m);
        for(int i=0; i<n; i++) cin >> s[i];
        for(int i=0; i<m; i++) cin >> t[i];

        sort(t.begin(),t.end());
        vector<vl> dp((1<<n), vl(m+1,1e18));
        vl sum(1<<n);
        for(int S=0; S<(1<<n); S++) {
            ll tmp = 0;
            for(int i=0; i<n; i++) {
                if(S & (1<<i)) tmp += s[i];
            }
            sum[S] = tmp;
        }
        // 経過日数0日
        for(int S=0; S<(1<<n); S++) dp[S][0] = 0;
        // 布団0枚
        for(int i=0; i<m; i++) {
            dp[0][i+1] = min(dp[0][i]+t[i],dp[0][i+1]);
        }

        for(int S=0; S<(1<<n); S++) {
            for(int i=0; i<n; i++) {
                if(S & (1<<n)) continue;
                for(int j=0; j<m; j++) {
                    dp[S|(1<<i)][j+1] = min({dp[S|(1<<i)][j]+abs(t[j]-sum[S|(1<<i)]),dp[S][j+1],dp[S|(1<<i)][j+1]});
                }
            }
        }
        cout << dp[(1<<n)-1][m] << endl;
    }
}
accuracy: 1
time_ms: 580
memory_kb: 30496
final_rank: 14

code_snippet: #pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

// #ifndef ONLINE_JUDGE
// #define _GLIBCXX_DEBUG // 配列外参照のエラー
// #endif

// スタンダードライブラリ
#include <bits/stdc++.h>
using namespace std;

// 型関連
using ll = long long;
using lint = long long;
using pll = pair<ll, ll>;
using plll = tuple<ll, ll, ll>;
using pii = pair<int, int>;
using piii = tuple<ll, ll, ll>;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vvvi = vector<vector<vector<int>>>;
using vvvvi = vector<vector<vector<vector<int>>>>;
using vl = vector<ll>;
using vvl = vector<vector<ll>>;
using vvvl = vector<vector<vector<ll>>>;
using vvvvl = vector<vector<vector<vector<ll>>>>;

template <class T> using prique = priority_queue<T>;

// 型定数
constexpr ll mod = 998244353;
constexpr ll MOD = 1000000007;
int INF32 = 2e9;
ll INF64 = 1e18;
#define endl '\n';

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

/////////////////////////// print関連
template <typename T> void print(vector<T> A);
void print();
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail);
void print(string S);
template <typename T> void print(vector<vector<T>> &F);

inline void Yes(bool f);

///////////////////ここから//////////////////////
bool solve() {

    int N, M;
    cin >> N >> M;
    if (N == 0) {
        return false;
    }
    vector<int> A(N);
    for (int i = 0; i < N; i++) {
        cin >> A[i];
    }
    vector<int> D(M);
    for (int j = 0; j < M; j++) {
        cin >> D[j];
    }
    sort(D.begin(),D.end());

    vector<ll> Nuku(1 << N);
    for (int S = 0; S < (1 << N); S++) {
        ll n = 0;
        for (int i = 0; i < N; i++) {
            if (S & (1 << i)) {
                n += A[i];
            }
        }
        Nuku[S] = n;
    }

    vvl dp(M * N + 1, vl(1 << N, INF64));
    for (int S = 0; S < (1 << N); S++) {
        dp[0][S] = 0;
    }

    vvi nex_S(1 << N);
    for (int S = 0; S < (1 << N); S++) {
        nex_S[S].emplace_back(S);
        for (int i = 0; i < N; i++) {
            if (S & (1 << i)) {
                continue;
            }
            nex_S[S].emplace_back(S|(1<<i));

        }
    }

    for (int i = 0; i < M * N; i++) {
        for (int S = 0; S < (1 << N); S++) {
            for (auto nS : nex_S[S]) {
                ll cost =
                    (i + 1) % N == 0 ? abs(D[(i + 1) / N - 1] - Nuku[nS]) : 0;
                dp[i + 1][nS] = min(dp[i + 1][nS], dp[i][S] + cost);
            }
        }
    }
    ll ans = INF64;
    for (int S = 0; S < (1 << N); S++) {
        ans = min(ans, dp[M * N][S]);
    }
    print(ans);

    return true;
}

int main() {
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    while (solve())
        ;
}

////////////////////print/////////////////////////
// 1次元ベクトルを出力する
template <typename T> void print(vector<T> A) {
    if (A.size() == 0) {
        return;
    }
    for (size_t i = 0; i < A.size() - 1; i++) {
        cout << A[i] << ' ';
    }
    cout << A[A.size() - 1] << endl;
    return;
}

// 2次元ベクトルを出力する
template <typename T> void print(vector<vector<T>> &F) {
    for (size_t i = 0; i < F.size(); i++) {
        for (size_t j = 0; j < F[i].size(); j++) {
            cout << F[i][j];
            if (j < F[i].size() - 1) {
                cout << ' ';
            }
        }
        cout << endl;
    }
}

// 空白行を出力するprint
void print() { cout << endl; }

// 数値・文字列を空白区切りで出力する. print(a,b)など
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail) {
    cout << head;
    if (sizeof...(tail) != 0)
        cout << " ";
    print(forward<Tail>(tail)...);
}

void print(string S) { cout << S << endl; }

//////////////出力関連

inline void Yes(bool f) {
    if (f) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
}
accuracy: 1
time_ms: 4510
memory_kb: 396676
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;

#include <atcoder/all>
using namespace atcoder;

using ll = long long;
using mint = modint998244353;

void chmin(int &x, int y) {
    if(x > y) x = y;
}

bool solve() {
    int N, M;
    cin >> N >> M;
    if(N == 0) return false;
    vector<int> S(N), D(M);
    for(int &x : S) cin >> x;
    for(int &x : D) cin >> x;

    vector<int> V(1 << N);
    for(int s = 0; s < 1 << N; ++s) {
        for(int i = 0; i < N; ++i) {
            V[s] += S[i] * ((s >> i) & 1);
        }
    }

    const int INF = 1 << 30;
    vector dp(M + 1, vector<int>(1 << N, INF));
    dp[0][0] = 0;
    sort(D.begin(), D.end());
    for(int i = 0; i < M; ++i) {
        for(int s = 0; s < 1 << N; ++s) {
            chmin(dp[i + 1][s], dp[i][s] + abs(D[i] - V[s]));
            for(int j = 0; j < N; ++j) chmin(dp[i][s | (1 << j)], dp[i][s]);
        }
    }

    cout << *min_element(dp[M].begin(), dp[M].end()) << endl;
    return true;
}

int main() {
    while(solve());
}
accuracy: 1
time_ms: 530
memory_kb: 16992
final_rank: 13

code_snippet: //#pragma GCC optimize("O3")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,n) for (ll i=0;i<(ll)n;i++)
#define rrep(i,n) for (ll i=n-1;i>=(ll)0;i--)
#define loop(i,m,n) for(ll i=m;i<=(ll)n;i++)
#define rloop(i,m,n) for(ll i=m;i>=(ll)n;i--)
#define vl vector<long long>
#define vvl vector<vector<long long>>
#define vdbg(a) rep(ii,a.size()){cout<<a[ii]<<" ";}cout<<endl;
#define vvdbg(a) rep(ii,a.size()){rep(jj,a[ii].size()){cout<<a[ii][jj]<<" ";}cout<<endl;}
#define setdbg(a) for(const auto & ii:a){cout<<ii<<" ";}cout<<endl;
#define inf 4000000000000000000LL
#define mod 998244353LL
#define eps 0.000000001
//#define mod 1000000007LL
random_device rnd;// 非決定的な乱数生成器
mt19937 mt(rnd());// メルセンヌ・ツイスタの32ビット版、引数は初期シード

//#include<boost/multiprecision/cpp_int.hpp>
//#define bbi boost::multiprecision::cpp_int

//#include<atcoder/lazysegtree>

//√の値が整数かを調べる
bool isSqrt(ll n) {
	if (n < 0) return false;
	ll sqrtN = static_cast<ll>(sqrt(n));
	return sqrtN * sqrtN == n;
}

//整数同士の累乗の計算をする。
ll power(ll A, ll B) {
	ll result = 1;
	for (ll i=0;i<B;i++){
		result *= A;
	}
	return result;
}

//素因数分解
vector<ll> makePrime(ll n){
	vector<ll> factors;
	while (n % 2 == 0) {
		factors.push_back(2);
		n /= 2;
	}
	for (ll i=3; i*i<=n;i+=2) {
		while (n%i == 0) {
			factors.push_back(i);
			n /= i;
		}
	}
	if (n > 2) {
		factors.push_back(n);
	}
	return factors;
}

//map形式で、nを素因数分解した値を返す
map<ll,ll> makeMapPrime(ll n){
	map<ll,ll> factors;
	while (n % 2 == 0) {
		factors[2]++;
		n /= 2;
	}
	for (ll i=3; i*i<=n;i+=2) {
		while (n%i == 0) {
			factors[i]++;
			n /= i;
		}
	}
	if (n > 2) {
		factors[n]++;
	}
	return factors;
}

// nのk乗をmodで割った余りを計算
ll power_mod(ll n, ll k){
	long long result = 1;
	while (k > 0){
		if ((k&1) ==1)result=(result*n)%mod;
		n=n*n%mod;
		k >>= 1;
	}
	return result;
}

//mod mにおけるaの逆元を計算
ll modinv(ll a, ll m) {
	ll b = m, u = 1, v = 0;
	while (b) {
		ll t = a / b;
		a -= t * b; swap(a, b);
		u -= t * v; swap(u, v);
	}
	u %= m; 
	if (u < 0) u += m;
	return u;
}

//場合の数 nCr を求める
ll ncr(ll n,ll r) {
	if(n<r)return 0;
	vvl dp(n+1,vl(r+1));
	rep (i,n+1)dp[i][0] = 1;
	rep (i,r+1)dp[i][i] = 1;
	loop (i,1,n){
		loop (j,1,min((ll)i-1,r)) {
			//nCr= n-1Cr-1 + n-1Cr
			dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
		}
	}
	return dp[n][r];
}

//受け取った文字列を、第2引数が0なら全て小文字に、1なら大文字に変換する関数
string cnvString(const string &str, int mode) {
	string result = str;
	if (mode == 0) {
		// 小文字に変換
		for (char &c : result) {
			c = tolower(c);
		}
	} else if (mode == 1) {
		// 大文字に変換
		for (char &c : result) {
			c = toupper(c);
		}
	}
	return result;
}

//第一引数で受け取った数を、第二引数で受け取った数の進数と見做して、第三引数の進数へ変換する。
string cnvBase(const string &str, ll from_base, ll to_base) {
	ll num = 0;
	//小文字があったら大文字に変換
	string num_str=cnvString(str,1);
	// 数値を10進数に変換
	for (char digit : num_str) {
		num = num * from_base + (isdigit(digit) ? digit - '0' : digit - 'A' + 10);
	}
	string result;
	// 数値を目的の基数に変換
	while (num > 0) {
		ll remainder = num % to_base;
		result.push_back(remainder < 10 ? remainder + '0' : remainder - 10 + 'A');
		num /= to_base;
	}
	// 結果を逆順にして返す
	reverse(result.begin(), result.end());
	return result.empty() ? "0" : result;
}

//底がaの対数xを計算。ただし小数点は繰り上げ。
ll logax(ll a, ll x){
	if(x<=1)return 0;
	ll result = 1;
	ll power = 1;
	while (power < (x+a-1) / a){
		power *= a;
		result++;
	}
	return result;
}

//第一引数を第二引数で割った余りを計算、割る数はint範囲
ll bigmd(const string &num, int md) {
	ll ans = 0;
	ll SIZ = 9; //9桁のチャンク
	ll base = 1000000000;//SIZ個の0
	rep(i,(num.size()-1)/SIZ+1){
		ll chunk = 0;
		ll l = i*SIZ;
		ll r = min((ll)num.size(),l+SIZ);
		if(r!=num.size()){
			ans = (ans*base+stoll(num.substr(l,r-l)))%md;
		}else{
			rep(i,r-l)ans*=10;
			ans=(ans+stoll(num.substr(l,r-l)))%md;
		}
	}
	return ans;
}

//受け取った2次元文字の外側に、文字pをコーティングする。
vector<string> pad(vector<string> &s,char p){
	ll h=s.size();
	ll w=s[0].size();
	vector<string> res(h+2,string(w+2,p));
	rep(i,h)rep(j,w)res[i+1][j+1]=s[i][j];
	return res;
}

//ax+by=cの整数解を得る ただし、cはgcd(a,b)の倍数でない場合、0,0になる
pair<ll,ll> ex_euclid(ll a,ll b,ll c){
	if(a<0||b<0||c<0){
		pair<ll,ll>ans=ex_euclid(abs(a),abs(b),abs(c));
		if(a<0)ans.first*=-1;
		if(b<0)ans.second*=-1;
		if(c<0)ans.first*=-1,ans.second*=-1;
		return ans;
	}
	if(c!=1){
		ll d=gcd(a,b);
		if(c%d!=0)return make_pair(0,0);
		pair<ll,ll>ans = ex_euclid(a/d,b/d,1);
		ans.first*=c/d;
		ans.second*=c/d;
		return ans;
	}
	if(a<b){
		pair<ll,ll>ans=ex_euclid(b,a,c);
		swap(ans.first,ans.second);
		return ans;
	}
	if(a==1&&b==0)return make_pair(1,0);
	else if(b==0) return make_pair(0,0);
	ll x,y;
	tie(x,y)=ex_euclid(b,a%b,c);
	pair<ll,ll> ans=make_pair(y,x-(a/b)*y);
	return ans;
}

//オイラーのトーシェント関数。N以下のNと互いに素な物の数を返す。
ll euler(ll n){
	unordered_map<ll,ll> factors;
	ll tmp=n;
	while (tmp % 2 == 0) {
		factors[2]++;
		tmp /= 2;
	}
	for (ll i=3; i*i<=tmp;i+=2) {
		while (tmp%i == 0) {
			factors[i]++;
			tmp/= i;
		}
	}
	if (tmp > 2)factors[tmp]++;
	ll ans=1;
	for(const auto & val:factors){
		ans*=power(val.first,val.second-1)*(val.first-1);
	}
	return ans;
}

// Union-Find
struct UnionFind {
	vector<int> par, siz;
	UnionFind(int n) : par(n, -1) , siz(n, 1) { }
	// 根を求める
	int root(int x) {
		if (par[x] == -1) return x;
		else return par[x] = root(par[x]);
	}
	// x と y が同じグループに属するかどうか (根が一致するかどうか)
	bool issame(int x, int y) {
		return root(x) == root(y);
	}
	// x を含むグループと y を含むグループとを併合する
	bool unite(int x, int y) {
		x = root(x), y = root(y);
		if (x == y) return false; 
		if (siz[x] < siz[y]) swap(x, y);
		par[y] = x;
		siz[x] += siz[y];
		return true;
	}
	// x を含むグループのサイズ
	int size(int x) {
		return siz[root(x)];
	}
};

//重み付きUF
struct PotentialUnionFind {
	ll n;
	vl par, siz, pot;
	PotentialUnionFind(ll N) : par(N,-1) , siz(N,1) , pot(N,0){n=N;}
	// 根を求める
	ll root(ll x) {
		if (par[x] == -1) return x;
		ll tmp = root(par[x]);
		pot[x] += pot[par[x]];
		par[x] = tmp;
		return par[x];
	}
	// x と y が同じグループに属するかどうか (根が一致するかどうか)
	bool issame(ll x, ll y) {
		return root(x) == root(y);
	}
	//x よりいくつ大きい所に y があるか。根が一致しない場合は"0"
	ll potential(ll x,ll y){
		if(root(x) != root(y)) return 0;
		else return pot[y]-pot[x];
	}
	//x より w だけ大きい状態として y を併合。
	bool unite(ll x, ll y, ll w) {
		ll rx = root(x),ry = root(y);
		if (rx == ry) return false;
		w += pot[x]-pot[y];
		if (siz[rx] < siz[ry]) swap(rx, ry),w*=-1;
		par[ry] = rx;
		siz[rx] += siz[ry];
		siz[ry] = 0;
		pot[ry] = w;
		return true;
	}
	// x を含むグループのサイズ
	ll size(ll x) {
		return siz[root(x)];
	}
	//小さい順にUnionFindグラフを調整、O(n log n)
	void regulation(){
		vvl r(n);
		rep(i,n)r[root(i)].push_back(i);
		rep(i,n){
			if(r[i].size()==0)continue;
			ll mn = i;
			rep(j,r[i].size())if(pot[mn]>pot[r[i][j]])mn=r[i][j];
			siz[mn]=siz[i];
			siz[i]=0;
			ll tmp = pot[mn];
			rep(j,r[i].size()){
				pot[r[i][j]]-=tmp;
				par[r[i][j]] = mn;
			}
			par[mn]=-1;
		}
	}
	void debug(){
		rep(i,n)cout<<setw(4)<<left<<par[i]<<" ";
		cout<<endl;
		rep(i,n)cout<<setw(4)<<left<<pot[i]<<" ";
		cout<<endl;
	}
};

//分離可能UnionFind、経路圧縮をしない。
struct CuttingFind{
	vector<int> par, siz;
	CuttingFind(int n) : par(n, -1) , siz(n, 1) { }
	// 根を求める
	int root(int x) {
		if (par[x] == -1) return x;
		else return root(par[x]);
	}
	// x と y が同じグループに属するかどうか (根が一致するかどうか)
	bool issame(int x, int y) {
		return root(x) == root(y);
	}
	//根x と 根y のグループを併合する(お互い根ではない時、falseで何もしない)
	bool unite(int x, int y) {
		if (issame(x,y) || par[x] != -1 || par[y] != -1) {
			cout<<"error"<<endl;
			return false;
		}
		if (siz[x] < siz[y]) swap(x, y);
		par[y] = x;
		siz[x] += siz[y];
		return true;
	}
	//根の側から、その直系の子供を分離する。片方が根でもう片方が直系の子でなければならない。
	bool separate(int x,int y){
		if(par[y]==-1)swap(x,y);
		if(par[y]!=x||par[x]!=-1){
			cout<<"error2"<<endl;
			return false;
		}
		siz[x] -= siz[y];
		par[y]=-1;
		return true;
	}
	// x を含むグループのサイズを求める
	int size(int x) {
		return siz[root(x)];
	}
};
//セグ木,乗せる値の型が必要
template<typename T>
struct SegTree{
	ll size;
	ll tall;
	vector<T> data;
	function<T(T,T)> p;
	//セグ木に乗せる値の初期値をa配列にし、putの関数をセグ木に乗せる、dをデフォルト値に。
	SegTree(vector<T> a,function<T(T,T)> put,T d) : data(power(2,logax(2,a.size())+1)) {
		size = data.size()/2;
		tall=logax(2,size)+1;
		p=put;
		ll tmp=size;
		data = vector<T>(size*2,d);
		while(tmp!=0){
			if(tmp==size)rep(i,a.size())data[tmp+i]=a[i];
			else rep(i,tmp) data[tmp+i]=p(data[2*(tmp+i)],data[2*(tmp+i)+1]);
			tmp/=2;
		}
	}
	//更新、t番目の値をxにする。
	void update(ll t,T x){
		t+=size;
		while(t!=0){
			if(t>=size)data[t]=x;
			else data[t]=p(data[2*t],data[2*t+1]);
			t/=2;
		}
	}
	//取得、l~r区間内の評価値を取得する。
	T get(ll l,ll r){
		//lとrが範囲外なら範囲内に正す
		l=max(0LL,l);
		r=min(r,size-1);
		r++;
		T ans=data[0];
		ll pos=l+size;
		ll wid=1;
		//出来る限り上に上げきる。
		while(l+(wid*2)<=r){
			while(l%(wid*2)==0&&l+(wid*2)<=r)pos/=2,wid*=2;
			ans=p(ans,data[pos]);
			pos++;
			l+=wid;
		}
		//上げ終わったので今度は下げる
		while(l!=r){
			while(l+wid>r)pos*=2,wid/=2;
			ans=p(ans,data[pos]);
			pos++;
			l+=wid;
		}
		return ans;
	}
	//セグ木デバッグ用、丸ごと出力
	void print(){
		rep(i,size)cout<<setw(7)<<left<<i;
		cout<<endl;
		ll pos=size;
		rep(i,tall){
			rep(j,size){
				if(j%power(2,i)==0)cout<<setw(7)<<left<<data[pos],pos++;
				else cout<<"       ";
			}
			pos/=4;
			cout<<endl;
		}
	}
};

//グリッド問題等用
vl dx={1,0,-1,0};
vl dy={0,1,0,-1};


ll solve(){
	ll n,m;
	cin>>n>>m;
	if(n==0&&m==0){return 1;}
	vl s(n),d(m);
	rep(i,n)cin>>s[i];
	rep(i,m)cin>>d[i];
	sort(d.begin(),d.end());

	vvl dp(m+1,vl(1<<n,inf));
	dp[0][0]=0;
	rep(i,m){
		rep(j,1<<n){
			//上方向へのゼータ変換
			rep(k,n){
				if(((1LL<<k)&j)==0){
					dp[i][j+(1LL<<k)]=min(dp[i][j],dp[i][j+(1LL<<k)]);
				}
			}

			//jの部分列を列挙
			ll b=j;
			ll nukumori=0;
			rep(k,n){
				if((1LL<<k)&j){
					nukumori+=s[k];
				}
			}
			ll tmp=abs(nukumori-d[i]);
			dp[i+1][j]=min(dp[i][j]+tmp,dp[i+1][j]);

			
		}
	}
	ll ans=inf;
	rep(i,1<<n){
		ans=min(ans,dp[m][i]);
	}
	cout<<ans<<endl;
	return 0;
}

//メイン
int main(){
	while(solve()==0);
	return 0;
}
accuracy: 1
time_ms: 2890
memory_kb: 30044
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define all(...) std::begin(__VA_ARGS__), std::end(__VA_ARGS__)
#define rall(...) std::rbegin(__VA_ARGS__), std::rend(__VA_ARGS__)
#define OVERLOAD_REP(_1, _2, _3, _4, name, ...) name
#define REP1(n) for(ll i=0;i<(n);i++)
#define REP2(i, n) for (ll i=0;i<(n);i++)
#define REP3(i, a, n) for (ll i=a;i<(n);i++)
#define REP4(i, a, b, n) for(ll i=a;i<(n);i+=b)
#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP4, REP3, REP2, REP1)(__VA_ARGS__)
#define OVERLOAD_RREP(_1, _2, _3, _4, name, ...) name
#define RREP1(n) for(ll i=(n)-1;i>=0;i--)
#define RREP2(i, n) for(ll i=(n)-1;i>=0;i--)
#define RREP3(i, a, n) for(ll i=(n)-1;i>=(a);i--)
#define RREP4(i, a, b, n) for(ll i=(n)-1;i>=(a);i-=(b))
#define rrep(...) OVERLOAD_RREP(__VA_ARGS__, RREP4, RREP3, RREP2, RREP1)(__VA_ARGS__)
#define uniq(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define len(n) (long long)(n).size()
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
using vs = vector<string>;
using vvs = vector<vs>;
using vvvs = vector<vvs>;
using vld = vector<ld>;
using vvld = vector<vld>;
using vvvld = vector<vvld>;
using vc = vector<char>;
using vvc = vector<vc>;
using vvvc = vector<vvc>;
using pll = pair<ll,ll>;
using vpll = vector<pll>;
using vvpll = vector<vpll>;

ll intpow(ll a,ll b){
    ll ans = 1;
    while (b){
        if (b & 1){
            ans *= a;
        }
        a *= a;
        b /= 2;
    }
    return ans;
}
ll modpow(ll a,ll b,ll c){
    ll ans = 1;
    while (b){
        if (b & 1){
            ans *= a;
            ans %= c;
        }
        a *= a;
        a %= c;
        b >>= 1;
    }
    return ans;
}

template<class... T>
void input(T&... a){
    (cin >> ... >> a);
}

#define INT(...) int __VA_ARGS__; input(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define STR(...) string __VA_ARGS__; input(__VA_ARGS__)
#define CHA(...) char __VA_ARGS__; input(__VA_ARGS__)
#define VLL(name,length) vll name(length);rep(i,length){cin >> name[i];}
#define VVLL(name,h,w) vvll name(h,vll(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVLL(name,a,b,c) vvvll name(a,vvll(b,vll(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VI(name,length) vi name(length);rep(i,length){cin >> name[i];}
#define VVI(name,h,w) vvi name(h,vi(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVI(name,a,b,c) vvvi name(a,vvll(b,vi(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VLD(name,length) vld name(length);rep(i,length){cin >> name[i];}
#define VVLD(name,h,w) vvld name(h,vld(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVLD(name,a,b,c) vvvld name(a,vvld(b,vld(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VC(name,length) vc name(length);rep(i,length){cin >> name[i];}
#define VVC(name,h,w) vvc name(h,vc(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVC(name,a,b,c) vvvc name(a,vvc(b,vc(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define VS(name,length) vs name(length);rep(i,length){cin >> name[i];}
#define VVS(name,h,w) vvs name(h,vs(w));rep(i,h)rep(j,w){cin >> name[i][j];}
#define VVVS(name,a,b,c) vvvs name(a,vvs(b,vs(c)));rep(i,a)rep(j,b)rep(k,c){cin >> name[i][j][k];}
#define PLL(name) pll name;cin>>name.first>>name.second;
#define VPLL(name,length) vpll name(length);rep(i,length){cin>>name[i].first>>name[i].second;}

void print(){cout << "\n";}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& p) {
    os << "(" << p.first << ", " << p.second << ")";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
    os << "[";
    for (size_t i = 0; i < vec.size(); ++i) {
        os << vec[i];
        if (i + 1 < vec.size()) os << ", ";
    }
    os << "]";
    return os;
}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::vector<std::pair<T1, T2>>& a) {
    os << "[";
    for (size_t j = 0; j < a.size(); ++j) {
        os << "(" << a[j].first << ", " << a[j].second << ")";
		if (j + 1 < a.size()) os << ", ";
    }
	os << "]";
    return os;
}

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<std::pair<T1, T2>>>& mat) {
	os << "[";
    for (size_t i = 0; i < mat.size(); ++i) {
		os << "[";
        for (size_t j = 0; j < mat[i].size(); ++j) {
            os << "(" << mat[i][j].first << ", " << mat[i][j].second << ")";
			if (j + 1 < mat[i].size()) os << ", ";
        }
		os << "]";
		if (i + 1 < mat.size()) os << ", ";
    }
	os << "]";
    return os;
}

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& s) {
    os << "{";
    bool first = true;
    for (const auto& x : s) {
        if (!first) os << ", ";
        os << x;
        first = false;
    }
    os << "}";
    return os;
}

template <typename K, typename V>
std::ostream& operator<<(std::ostream& os, const std::map<K, V>& m) {
    os << "{";
    bool first = true;
    for (const auto& [key, val] : m) {
        if (!first) os << ", ";
        os << key << ": " << val;
        first = false;
    }
    os << "}";
    return os;
}

template<class T, class... Ts>
void print(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}

void write(){cout << "\n";}
template<class T, class... Ts>
void write(const T& a, const Ts&... b){cout << a;(cout << ... << (cout << ' ', b));cout << '\n';}
void write(vll x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvll x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vi x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvi x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vvvi x){rep(i,len(x))rep(j,len(x[i]))rep(k,len(x[i][j])){cout << x[i][j][k];if(k!=len(x[i][j])-1){cout << " ";}else if(j!=len(x[i])-1){cout << " | ";}else{cout << '\n';}}}
void write(vld x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvld x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vvvld x){rep(i,len(x))rep(j,len(x[i]))rep(k,len(x[i][j])){cout << x[i][j][k];if(k!=len(x[i][j])-1){cout << " ";}else if(j!=len(x[i])-1){cout << " | ";}else{cout << '\n';}}}
void write(vc x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << " ";}else{cout << '\n';}}}
void write(vvc x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << "";}else{cout << '\n';}}}
void write(vvvc x){rep(i,len(x))rep(j,len(x[i]))rep(k,len(x[i][j])){cout << x[i][j][k];if(k!=len(x[i][j])-1){cout << " ";}else if(j!=len(x[i])-1){cout << " | ";}else{cout << '\n';}}}
void write(vs x){rep(i,len(x)){cout << x[i];if(i!=len(x)-1){cout << "\n";}else{cout << '\n';}}}
void write(vvs x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j];if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}
void write(vvvs x){rep(i,len(x))rep(j,len(x[i]))rep(k,len(x[i][j])){cout << x[i][j][k];if(k!=len(x[i][j])-1){cout << " ";}else if(j!=len(x[i])-1){cout << " | ";}else{cout << '\n';}}}
void write(pll x){cout << x.first << ' ' << x.second << '\n';}
void write(vpll x){rep(i,len(x)){cout << x[i].first << ' ' << x[i].second << '\n';}}
void write(vvpll x){rep(i,len(x))rep(j,len(x[i])){cout << x[i][j].first << ' ' << x[i][j].second;if(j!=len(x[i])-1){cout << " ";}else{cout << '\n';}}}

template <typename T>
T sum(const std::vector<T>& v) {
    return std::accumulate(v.begin(), v.end(), T(0));
}

template<class T> bool chmin(T& a, const T& b){ if(a > b){ a = b; return 1; } return 0; }
template<class T> bool chmax(T& a, const T& b){ if(a < b){ a = b; return 1; } return 0; }
template<class T, class U> bool chmin(T& a, const U& b){ if(a > T(b)){ a = b; return 1; } return 0; }
template<class T, class U> bool chmax(T& a, const U& b){ if(a < T(b)){ a = b; return 1; } return 0; }

int main(){
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    while(1){
        LL(n,m);
        if(n + m == 0){break;}
        VLL(s,n);
        VLL(d,m);
        vll dp(1<<n,1LL<<60);
        ll x = sum(d);
        dp[0] = x;
        auto f = [&](ll p, ll v){
            ll temp = 0;
            rep(j,m){
                if(d[j] >= p){
                    temp -= d[j] - p;
                    temp += min(abs(d[j]-p),abs(d[j]-v));
                }
            }
            return temp;
        };
        rep(i,(1LL<<n)){
            ll p = 0;
            rep(j,n){
                if(((i >> j) & 1) == 1){
                    p += s[j];
                }
            }
            rep(j,n){
                if(((i >> j) & 1) == 1){continue;}
                chmin(dp[i | (1<<j)],dp[i] + f(p,p+s[j]));
            }
        }
        write(dp.back());
    }
    
}
accuracy: 1
time_ms: 230
memory_kb: 3820
final_rank: 3

code_snippet: // AOJ #2749
// The Most Powerful Bed 2025.2.11

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
 
vector<ll> demands;
vector<ll> pref;
 
ll costInterval(ll L, ll R) {
    int i = int(lower_bound(demands.begin(), demands.end(), L) - demands.begin());
    int j = int(upper_bound(demands.begin(), demands.end(), R) - demands.begin());
    if(i >= j) return 0;
    ll mid = (L + R) / 2;
    int k = int(lower_bound(demands.begin() + i, demands.begin() + j, mid+1) - demands.begin());
    int cntLeft = k - i;
    ll sumLeft = pref[k] - pref[i];
    ll costLeft = sumLeft - (ll)cntLeft * L;
    int cntRight = j - k;
    ll sumRight = pref[j] - pref[k];
    ll costRight = (ll)cntRight * R - sumRight;
    return costLeft + costRight;
}
 
int N;
vector<ll> s;
vector<ll> maskSum;
ll Ttotal;
vector<ll> dpMemo;
 
ll dp(int mask) {
    int full = (1 << N) - 1;
    if(mask == full) return costInterval(maskSum[mask], Ttotal);
    if(dpMemo[mask] != -1) return dpMemo[mask];
    ll current = maskSum[mask];
    ll best = LLONG_MAX;
    for(int i = 0; i < N; i++){
        if(!(mask & (1 << i))){
            ll nextVal = current + s[i];
            ll cand = costInterval(current, nextVal) + dp(mask | (1 << i));
            best = min(best, cand);
        }
    }
    dpMemo[mask] = best;
    return best;
}
 
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
 
    while(true){
        int M;
        cin >> N >> M;
        if(N == 0) break;
 
        s.resize(N);
        Ttotal = 0;
        for (int i = 0; i < N; i++){
            cin >> s[i];
            Ttotal += s[i];
        }
 
        vector<ll> d(M);
        for (int j = 0; j < M; j++) cin >> d[j];
 
        vector<ll> dLE, dGT;
        for (int j = 0; j < M; j++){
            if(d[j] <= Ttotal) dLE.push_back(d[j]);
            else dGT.push_back(d[j]);
        }
 
        sort(dLE.begin(), dLE.end());
        demands = dLE;
        pref.resize(demands.size()+1);
        pref[0] = 0;
        for (size_t i = 0; i < demands.size(); i++)
            pref[i+1] = pref[i] + demands[i];
 
        ll extra = 0;
        for (ll val : dGT) extra += (val - Ttotal);
 
        int totalStates = 1 << N;
        maskSum.assign(totalStates, 0);
        for(int mask = 0; mask < totalStates; mask++){
            ll sumVal = 0;
            for(int i = 0; i < N; i++)
                if(mask & (1 << i)) sumVal += s[i];
            maskSum[mask] = sumVal;
        }
        dpMemo.assign(totalStates, -1);
        ll ans = dp(0) + extra;
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 120
memory_kb: 3544
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define int long long
#define sz(x) (int)x.size()


signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n, m;
    while(cin >> n >> m){
        if (!n && !m)break;
        vector<int>s(n), d(m);
        for (auto &x : s)cin >> x;
        for (auto &x : d)cin >> x;

        int dp[1 << n], sum[1 << n];
        memset(dp, 0, sizeof(dp));
        for (int mask = 0; mask < (1 << n); mask++){
            sum[mask] = 0;
            for (int i = 0; i < n; i++){
                if ((mask >> i) & 1)
                    sum[mask] += s[i];
            }
        }

        sort(d.begin(), d.end());
        for (int i = 0; i < m; i++){
            for (int mask = 0; mask < (1 << n); mask++){
                for (int j = 0; j < n; j++){
                    int nmask = mask | (1 << j);
                    dp[nmask] = min(dp[mask], dp[nmask]);
                }
                dp[mask] += abs(sum[mask] - d[i]);
            }
        }
        cout << *min_element(dp, dp + (1 << n)) << "\n";
    }
    
    return 0;
}
accuracy: 1
time_ms: 590
memory_kb: 3956
final_rank: 11

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double x) {
    wt_real(x);
}

template <class T, class U> void wt(const pair<T, U> val) {
    wt(val.first);
    wt(' ');
    wt(val.second);
}
template <size_t N = 0, typename T> void wt_tuple(const T t) {
    if constexpr (N < std::tuple_size<T>::value) {
        if constexpr (N > 0) {
            wt(' ');
        }
        const auto x = std::get<N>(t);
        wt(x);
        wt_tuple<N + 1>(t);
    }
}
template <class... T> void wt(tuple<T...> tpl) {
    wt_tuple(tpl);
}
template <class T, size_t S> void wt(const array<T, S> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}
template <class T> void wt(const vector<T> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}

void print() {
    wt('\n');
}
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail) {
    wt(head);
    if (sizeof...(Tail))
        wt(' ');
    print(forward<Tail>(tail)...);
}
void __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

template <unsigned mod = 1000000007> struct fp {
    unsigned v;
    static constexpr int get_mod() {
        return mod;
    }
    constexpr unsigned inv() const {
        assert(v != 0);
        int x = v, y = mod, p = 1, q = 0, t = 0, tmp = 0;
        while (y > 0) {
            t = x / y;
            x -= t * y, p -= t * q;
            tmp = x, x = y, y = tmp;
            tmp = p, p = q, q = tmp;
        }
        if (p < 0)
            p += mod;
        return p;
    }
    constexpr fp(ll x = 0) : v(x >= 0 ? x % mod : (mod - (-x) % mod) % mod) {}
    fp operator-() const {
        return fp() - *this;
    }
    fp pow(ull t) {
        fp res = 1, b = *this;
        while (t) {
            if (t & 1)
                res *= b;
            b *= b;
            t >>= 1;
        }
        return res;
    }
    fp &operator+=(const fp &x) {
        if ((v += x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator-=(const fp &x) {
        if ((v += mod - x.v) >= mod)
            v -= mod;
        return *this;
    }
    fp &operator*=(const fp &x) {
        v = ull(v) * x.v % mod;
        return *this;
    }
    fp &operator/=(const fp &x) {
        v = ull(v) * x.inv() % mod;
        return *this;
    }
    fp operator+(const fp &x) const {
        return fp(*this) += x;
    }
    fp operator-(const fp &x) const {
        return fp(*this) -= x;
    }
    fp operator*(const fp &x) const {
        return fp(*this) *= x;
    }
    fp operator/(const fp &x) const {
        return fp(*this) /= x;
    }
    bool operator==(const fp &x) const {
        return v == x.v;
    }
    bool operator!=(const fp &x) const {
        return v != x.v;
    }
    friend istream &operator>>(istream &is, fp &x) {
        return is >> x.v;
    }
    friend ostream &operator<<(ostream &os, const fp &x) {
        return os << x.v;
    }
};

template <unsigned mod> void rd(fp<mod> &x) {
    fastio::rd(x.v);
}
template <unsigned mod> void wt(fp<mod> x) {
    fastio::wt(x.v);
}

template <typename T> T Inv(ll n) {
    static const int md = T::get_mod();
    static vector<T> buf({0, 1});
    assert(n > 0);
    n %= md;
    while (SZ(buf) <= n) {
        int k = SZ(buf), q = (md + k - 1) / k;
        buf.push_back(buf[k * q - md] * q);
    }
    return buf[n];
}

template <typename T> T Fact(ll n, bool inv = 0) {
    static const int md = T::get_mod();
    static vector<T> buf({1, 1}), ibuf({1, 1});
    assert(n >= 0 and n < md);
    while (SZ(buf) <= n) {
        buf.push_back(buf.back() * SZ(buf));
        ibuf.push_back(ibuf.back() * Inv<T>(SZ(ibuf)));
    }
    return inv ? ibuf[n] : buf[n];
}

template <typename T> T nPr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nCr(int n, int r, bool inv = 0) {
    if (n < 0 || n < r || r < 0)
        return 0;
    return Fact<T>(n, inv) * Fact<T>(r, inv ^ 1) * Fact<T>(n - r, inv ^ 1);
}
template <typename T> T nHr(int n, int r, bool inv = 0) {
    return nCr<T>(n + r - 1, r, inv);
}

/**
 * @brief Modint
 */

int main() {
while(1) {
    int N, M;
    cin >> N >> M;
    if (N == 0 && M == 0) return 0;
    vector<int> S(N), D(M);
    rep(i,0,N) cin >> S[i];
    rep(i,0,M) cin >> D[i];
    vector<int> SUM(1<<N,0), DP(1<<N, inf);
    rep(i,0,1<<N) {
        rep(j,0,N) {
            if ((i & (1<<j)) == (1<<j)) SUM[i] += S[j];
        }
    }
    DP[0] = 0;
    rep(i,0,1<<N) {
        rep(j,0,N) {
            if ((i & (1<<j)) == 0) {
                int COUNT = DP[i];
                rep(k,0,M) {
                    if (SUM[i] <= D[k] && D[k] <= SUM[i | (1<<j)]) COUNT += min(D[k]-SUM[i], SUM[i | (1<<j)] - D[k]);
                }
                chmin(DP[i | (1<<j)], COUNT);
            }
        }
    }
    int ANS = DP[(1<<N)-1];
    rep(i,0,M) {
        if (SUM[(1<<N)-1]<D[i]) ANS += D[i]-SUM[(1<<N)-1];
    }
    cout << ANS << endl;
}
}
accuracy: 1
time_ms: 390
memory_kb: 3684
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (long long i = 0; i < (long long)(n); i++)
#define rrep(i,start,end) for (long long i = start;i >= (long long)(end);i--)
#define repn(i,end) for(long long i = 0; i <= (long long)(end); i++)
#define reps(i,start,end) for(long long i = start; i < (long long)(end); i++)
#define repsn(i,start,end) for(long long i = start; i <= (long long)(end); i++)
#define each(p,a) for(auto &p:a)
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef vector<long long> vll;
typedef vector<pair<long long ,long long>> vpll;
typedef vector<vector<long long>> vvll;
typedef set<ll> sll;
typedef map<long long , long long> mpll;
typedef pair<long long ,long long> pll;
typedef tuple<long long , long long , long long> tpl3;
#define LL(...) ll __VA_ARGS__; input(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__; input(__VA_ARGS__)
#define Str(...) string __VA_ARGS__; input(__VA_ARGS__)
#define Ch(...) char __VA_ARGS__; input(__VA_ARGS__)
#define all(a)  (a).begin(),(a).end()
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );
#define sz(x) (int)x.size()
// << std::fixed << std::setprecision(10)
const ll INF = 1LL << 60;
const ld EPS = 1e-9;
 
inline ll lfloor(ll x,ll m){return (x - ((x % m+ m)%m))/m;}
inline ll positive_mod(ll a,ll m){return (a % m + m)%m;}
inline ll popcnt(ull a){ return __builtin_popcountll(a);}
template<class T> bool chmin(T& a, T b){if(a > b){a = b;return true;}return false;}
template<class T> bool chmax(T& a, T b){if(a < b){a = b;return true;}return false;}
template<typename T> std::istream &operator>>(std::istream&is,std::vector<T>&v){for(T &in:v){is>>in;}return is;}
template<typename T> std::ostream &operator<<(std::ostream&os,const std::vector<T>&v){for(auto it=std::begin(v);it!=std::end(v);){os<<*it<<((++it)!=std::end(v)?" ":"");}return os;}
template<typename T1, typename T2>std::ostream &operator<< (std::ostream &os, std::pair<T1,T2> p){os << "{" << p.first << "," << p.second << "}";return os;}
template<class... T>void input(T&... a){(cin >> ... >> a);}
void print(){cout << endl;}
template<class T, class... Ts>void print(const T& a, const Ts&... b){cout << a;((cout << ' ' << b), ...);cout << endl;}
template<class T> void pspace(const T& a){ cout << a << ' ';}
void perr(){cerr << endl;}
template<class T, class... Ts>void perr(const T& a, const Ts&... b){cerr << a;((cerr << ' ' << b), ...);cerr << endl;}
void yes(bool i = true){ return print(i?"yes":"no"); }
void Yes(bool i = true){ return print(i?"Yes":"No"); }
void YES(bool i = true){ return print(i?"YES":"NO"); }
template <class T> vector<T> &operator++(vector<T> &v) {for(auto &e : v) e++;return v;}
template <class T> vector<T> operator++(vector<T> &v, signed) {auto res = v;for(auto &e : v) e++;return res;}
template <class T> vector<T> &operator--(vector<T> &v) {for(auto &e : v) e--;return v;}
template <class T> vector<T> operator--(vector<T> &v, signed) {auto res = v;for(auto &e : v) e--;return res;}
//grid探索用
vector<ll> _ta = {0,0,1,-1,1,1,-1,-1};
vector<ll> _yo = {1,-1,0,0,1,-1,1,-1};
bool isin(ll now_i,ll now_j,ll h,ll w){return (0<=now_i && now_i < h && 0 <= now_j && now_j < w);}
  
ll lpow(ll x,ll n){ll ans = 1;while(n >0){if(n & 1)ans *= x;x *= x;n >>= 1;}return ans;}
ll Modlpow(ll x,ll n,ll m){ll ans = 1;ll a = x%m;while(n >0){if(n & 1){ans *= a;ans%= m;}a *= a;a %= m;n >>= 1;}return ans;} 
const ll MOD9 = 998244353LL;
const ll MOD10 = 1000000007LL;

// for AOJ or ICPC or etc..
// 全部が0だったらtrueを返す
template<class Tp> bool zero (const Tp &x) {return x == 0;}
template<class Tp, class... Args> bool zero (const Tp &x, const Args& ...args) {return zero(x) and zero(args...);}


// 変数をちゃんと全部受け取る！
void solve(ll n,ll m){
  vll s(n),d(m);
  cin >> s >> d;
  sort(all(d));
  vll sum(1 << n);
  rep(i,1 << n){
    ll sm = 0;
    rep(j,n){
      if(i >> j & 1){
        sm += s[j];
      }
    }
    sum[i] = sm;
  }
  vvll dp(m+1,vector<ll>(1 << n,INF));
  rep(i,1 << n){
    dp[0][i] = 0;
  }
  rep(i,m){
    rep(j,1 << n){
      if(dp[i][j] == INF)continue;
      chmin(dp[i+1][j],dp[i][j] +  abs(sum[j]-d[i]));
      rep(k,n){
        if(~j >> k & 1){
          chmin(dp[i+1][j+(1<<k)],dp[i][j] + abs(sum[j+(1<<k)]-d[i]));
          chmin(dp[i][j+(1<<k)],dp[i][j]);
        }
      }
    }
  }
  // rep(i,m+1){
  //   rep(j,1 << n){
  //     cout << dp[i][j] << " ";
  //   }
  //   cout << endl;
  // }
  ll ans = accumulate(all(d),0LL);
  rep(i,1 << n){
    chmin(ans,dp[m][i]);
  }
  cout << ans << endl;
}
 
int main(){
  ios::sync_with_stdio(false);cin.tie(nullptr);
  while(true){
    LL(n,m);//変数数調整
    if(zero(n,m))break;
    solve(n,m);
  }
}
accuracy: 1
time_ms: 1680
memory_kb: 29952
final_rank: 17

code_snippet: #if 1
// clang-format off
#include <bits/stdc++.h>

using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
using lf = long double;
using pll = pair<ll, ll>;
#define vec vector
template <class T> using v = vector<T>;
template <class T> using vv = v<v<T>>;
template <class T> using vvv = v<vv<T>>;
using vl = v<ll>;
using vvl = vv<ll>;
using vvvl = vvv<ll>;
using vpl = v<pll>;
using vs = v<string>;
using vb = v<bool>;
using vvb = v<vb>;
using vvvb = v<vvb>;
template<class T> using PQ = priority_queue<T, v<T>, greater<T>>;
constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n - 1); }

#define FOR(i, a, b) for (ll i = (ll)(a); i < (ll)(b); i++)
#define rep(i, N) for (ll i = 0; i < (ll)(N); i++)
#define rep1(i, N) for (ll i = 1; i <= (ll)(N); i++)
#define rrep(i, N) for (ll i = N - 1; i >= 0; i--)
#define rrep1(i, N) for (ll i = N; i > 0; i--)
#define fore(i, a) for (auto &i : a)
#define fs first
#define sc second
#define eb emplace_back
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define UNIQUE(x) (x).erase(unique((x).begin(), (x).end()), (x).end());
#define YES(x) cout << ((x) ? "YES\n" : "NO\n");
#define Yes(x) cout << ((x) ? "Yes\n" : "No\n");
#define yes(x) cout << ((x) ? "yes\n" : "no\n");
template <class T, class U> void chmin(T &t, const U &u) { if (t > u) t = u; }
template <class T, class U> void chmax(T &t, const U &u) { if (t < u) t = u; }
template <class T> T min(const v<T> &lis) { return *min_element(all(lis)); }
template <class T> T max(v<T> &lis) { return *max_element(all(lis)); }
const int inf = (1 << 30);
const ll infl = (1LL << 60);
const ll mod93 = 998244353;
const ll mod17 = 1000000007;
int popcnt(uint x) { return __builtin_popcount(x); }
int popcnt(ull x) { return __builtin_popcountll(x); }
// 桁数
int bsr(uint x) { return 31 - __builtin_clz(x); }
int bsr(ull x) { return 63 - __builtin_clzll(x); }
// 2で割れる回数
int bsf(uint x) { return __builtin_ctz(x); }
int bsf(ull x) { return __builtin_ctzll(x); }

template <class T, class S> istream &operator>>(istream &is, pair<T, S> &x) { return is >> x.first >> x.second; }
template <class T, class S> ostream &operator<<(ostream &os, const pair<T, S> &x) { return os << x.first << " " << x.second; }
template <class T> istream &operator>>(istream &is, vector<T> &x) { for (auto &y : x) is >> y; return is; }
template <class T> ostream &operator<<(ostream &os, const vector<T> &x) {
  for (size_t i = 0, size = x.size(); i < size; i++)
    os << x[i] << (i == size - 1 ? "" : " ");
  return os;
}

ll rand_int(ll l, ll r) {  // [l, r]
  static random_device rd;
  static mt19937 gen(rd());
  return uniform_int_distribution<ll>(l, r)(gen);
}

// #include <boost/multiprecision/cpp_int.hpp>
// using cpp_int = boost::multiprecision::cpp_int;

// clang-format on
#endif

// #define _GLIBCXX_DEBUG

struct Solver {
  void solve(ll n, ll m) {
    vl s(n), d(m);
    cin >> s >> d;
    sort(all(d));
    ll k = 1 << n;
    vl sum(k);
    rep(i, k) {
      rep(j, n) {
        if ((i >> j) & 1) sum[i] += s[j];
      }
    }
    vl dp(k);
    rep(i, m) {
      rep(j, k) {
        dp[j] += abs(d[i] - sum[j]);
      }
      rep(j, k) {
        rep(l, n)
          chmin(dp[j|(1<<l)], dp[j]);
      }
    }
    cout << dp[k - 1] << "\n";
  }
};

int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(20);

  ll t = 1;
  // cin >> t;
  while (t) {
    ll n, m;
    cin >> n >> m;
    if (n == 0 && m == 0) break;
    Solver solver;
    solver.solve(n, m);
  }
}
accuracy: 1
time_ms: 500
memory_kb: 3568
final_rank: 10

code_snippet: #include <bits/stdc++.h>

bool solve() {
    int N, M;
    std::cin >> N >> M;
    if (N == 0 and M == 0) return false;
    std::vector<int> S(N);
    for (auto& s : S) std::cin >> s;
    std::vector<int> D(M);
    for (auto& d : D) std::cin >> d;
    std::sort(D.begin(), D.end());
    std::vector<int> sum(1 << N);
    for (int bit{} ; bit < (1 << N) ; bit++) {
        for (int i{} ; i < N ; i++) if (bit & (1 << i)) {
            sum[bit] += S[i];
        }
    }

    const long long INF{(long long)1e18};
    std::vector<long long> dp(1 << N, INF);
    dp[0] = std::accumulate(D.begin(), D.end(), 0LL);
    for (int bit{} ; bit < (1 << N) ; bit++) {
        assert(dp[bit] < INF);
        int low{(int)std::distance(D.begin(), std::upper_bound(D.begin(), D.end(), sum[bit]))};
        for (int i{} ; i < N ; i++) {
            if (bit & (1 << i)) continue;
            int nextbit{bit | (1 << i)};
            long long cost{dp[bit]};
            for (int j{low} ; j < M ; j++) {
                assert(D[j] > sum[bit]);
                cost -= D[j] - sum[bit];
            }
            //std::cout << bit << ' ' << dp[bit] << ' ' << cost << std::endl;
            assert(cost >= 0);
            for (int j{low} ; j < M ; j++) {
                cost += std::min(std::abs(D[j] - sum[bit]), std::abs(D[j] - sum[nextbit]));
            }
            dp[nextbit] = std::min(dp[nextbit], cost);
        }
    }
    std::cout << *std::min_element(dp.begin(), dp.end()) << '\n';
    return true;
}

int main() {
    std::cin.tie(nullptr)->sync_with_stdio(false);

    while (solve()) ;
}
accuracy: 1
time_ms: 310
memory_kb: 3780
final_rank: 6

code_snippet: #include<iostream>
#include<algorithm>
using namespace std;
int N,M,A[15],D[100],S[1<<15];
int dp[1<<15];
bool solve()
{
    cin>>N>>M;
    if(N==0&&M==0)return 0;
    for(int i=0;i<N;i++)cin>>A[i];
    for(int i=0;i<M;i++)cin>>D[i];
    sort(D,D+M);
    for(int i=0;i<1<<N;i++)
    {
        S[i]=0;
        for(int j=0;j<N;j++)if(i>>j&1)S[i]+=A[j];
    }
    for(int i=0;i<1<<N;i++)dp[i]=1<<30;
    dp[0]=0;
    for(int k=0;k<M;k++)dp[0]+=D[k];
    for(int i=1;i<1<<N;i++)
    {
        for(int j=0;j<N;j++)if(i>>j&1)
        {
            int pre=i^(1<<j);
            int add=0;
            for(int k=0;k<M;k++)if(D[k]>=S[pre])
            {
                add-=D[k]-S[pre];
                add+=min(abs(D[k]-S[pre]),abs(D[k]-S[i]));
            }
            dp[i]=min(dp[i],dp[pre]+add);
        }
    }
    cout<<dp[(1<<N)-1]<<'\n';
    return 1;
}
int main(){while(solve()){}}
accuracy: 1
time_ms: 260
memory_kb: 3616
final_rank: 5

code_snippet: #include <bits/stdc++.h>

int solve() {
    int n, m;
    std::cin >> n >> m;
    if (n == 0) return 1;
    std::vector<int> s(n), t(m);
    for (int i = 0; i < n; i++) std::cin >> s[i];
    for (int i = 0; i < m; i++) std::cin >> t[i];
    std::vector<int> sum(1 << n);
    for (int i = 0; i < (1 << n); i++) {
        for (int j = 0; j < n; j++) {
            if (i & (1 << j)) {
                sum[i] += s[j];
            }
        }
    }
    std::sort(t.begin(), t.end());
    std::vector<int> dp(1 << n);
    for (int i = 0; i < m; i++) {
        std::vector<int> ndp(1 << n);
        for (int j = 0; j < (1 << n); j++) {
            ndp[j] = dp[j] + std::abs(t[i] - sum[j]);
        }
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < (1 << n); k++) {
                if ((k & (1 << j)) == 0) {
                    ndp[k | (1 << j)] = std::min(ndp[k | (1 << j)], ndp[k]);
                }
            }
        }
        dp = std::move(ndp);
    }
    std::cout << *std::min_element(dp.begin(), dp.end()) << '\n';
    return 0;
}

int main() {
    while (!solve());
}
accuracy: 1
time_ms: 380
memory_kb: 3556
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
#define rep(i, a, b) for(ll i = a; i < b; ++i)
#define rrep(i, a, b) for(ll i = a; i >= b; --i)
constexpr ll inf = 4e18;
using Real = long double;
const Real EPS = 1e-8, PI = acos(Real(-1.0));
int sign(const Real& r) {
    if(r <= -EPS) return -1;
    if(r >= +EPS) return +1;
    return 0;
}
bool eq(const Real& a, const Real& b) {
    return sign(a - b) == 0;
}
using Point = complex<Real>;
istream& operator>>(istream& is, Point& p) {
    Real a, b;
    is >> a >> b;
    p = Point(a, b);
    return is;
}
ostream& operator<<(ostream& os, const Point& p) {
    return os << p.real() << ' ' << p.imag();
}
Real cross(const Point& p1, const Point& p2) {
    return (conj(p1) * p2).imag();
}
Real area(const vector<Point>& polygon) {
    Real res = 0.0;
    int n = polygon.size();
    rep(i, 0, n) {
        res += cross(polygon[i], polygon[(i + 1) % n]);
    }
    return abs(res * 0.5);
}
int main(void) {
    cin.tie(0);
    ios::sync_with_stdio(0);
    while(1) {
        ll n,m;cin>>n>>m;
        if(n == 0 && m == 0) {
            break;
        }
        vector<ll> s(n);rep(i,0,n)cin>>s[i];
        vector<ll> d(m);rep(i,0,m)cin>>d[i];
        d.push_back(0);
        sort(d.begin(), d.end());
        
        ll N = (1LL << n);
        vector<vector<ll>> dp(m+1, vector<ll>(N, inf));
        dp[0][0] = 0;

        vector<ll> sum_s(N, 0);
        rep(i,0,N){
            rep(j,0,n){
                if((i>>j)&1) {
                    sum_s[i] += s[j];
                }
            }
        }

        rep(i,0,m){
            vector<ll> sub_min(N, inf);
            rep(j,0,N){
                sub_min[j] = dp[i][j];
                rep(k,0,n){
                    if((j>>k)&1) {
                        sub_min[j] = min(sub_min[j], sub_min[j - (1LL << k)]);
                    }
                }
            }

            rep(j,0,N){
                dp[i+1][j] = min(dp[i+1][j], sub_min[j] + abs(sum_s[j] - d[i+1]));
                // for(ll k = 0; k <= j; k = (k+1) & j) {
                //     dp[i+1][j] = min(dp[i+1][j], dp[i][k] + abs(sum_s[j] - d[i+1]));
                //     if (k == j)break;
                // }
            }
        }
        ll ans = inf;
        rep(j,0,N){
            ans = min(ans, dp[m][j]);
        }
        cout << ans << "\n";
    }
}
accuracy: 1
time_ms: 1460
memory_kb: 29908
final_rank: 16

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

int solve(int N, int M) {
    vector<int> s = in(N), d = in(M);

    vector<int> dp(1 << N, 1e9);
    dp[0] = sum_of<int>(d);
    for(int S : rep(1 << N)) {
        int sum = 0;
        for(int i : rep(N)) if(S & (1 << i)) sum += s[i];
        for(int i : rep(N)) if(!(S & (1 << i))) {
            int score = dp[S];
            for(int j : rep(M)) {
                if(sum <= d[j]) {
                    score -= abs(sum - d[j]);
                    score += min(abs(sum - d[j]), abs(sum + s[i] - d[j]));
                }
            }
            chmin(dp[S | (1 << i)], score);
        }
    }

    return dp[(1 << N) - 1];
}

int main() {
    while(true) {
        int N = in(), M = in();
        if(make_pair(N, M) == make_pair(0, 0)) return 0;
        print(solve(N, M));
    }
}
accuracy: 1
time_ms: 250
memory_kb: 3504
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;

template<class T>
bool chmin(T &a, const T &b) {if (a > b) {a = b; return 1;} return 0;}

using ll = long long;

bool is_end = false;

const ll INF = 1e18;
ll dp[1<<15];

void init()
{
	for (int i = 0; i < (1<<15); ++i)
	{
		dp[i] = INF;
	}
	
	return;
}

void calc()
{
	ll N, M; cin >> N >> M;
	if (N == 0) {is_end = true; return;}
	
	vector<ll> S(N), D(M);
	for (int i = 0; i < N; ++i) {cin >> S[i];}
	for (int i = 0; i < M; ++i) {cin >> D[i];}
	sort(D.begin(), D.end());
	
	init();
	dp[0] = 0;
	for (int bit = 1; bit < (1<<N); ++bit)
	{
		ll sum = 0;
		for (int i = 0; i < N; ++i)
		{
			sum += (bit & (1<<i) ? S[i] : 0);
		}
		
		for (int lst = 0; lst < N; ++lst)
		{
			if (!(bit & (1<<lst))) {continue;}
			
			int pbit = bit ^ (1<<lst);
			ll psum = sum - S[lst];
			auto itr = lower_bound(D.begin(), D.end(), psum);
			
			ll diff = 0;
			while (itr != D.end() && *itr < sum)
			{
				ll d = *itr;
				diff += min(abs(d - psum), abs(sum - d));
				itr++;
			}
			chmin(dp[bit], dp[pbit] + diff);
		}		
	}
	
	ll res = dp[(1<<N)-1];
	ll sum = accumulate(S.begin(), S.end(), 0LL);
	for (int i = 0; i < M; ++i)
	{
		res += max(0LL, D[i] - sum);
	}
	cout << res << endl;
	
	return;
}

int main()
{
	while (!is_end)
	{
		calc();
	}
	
	return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 3476
final_rank: 1

code_snippet: #include <vector>
#include <iostream>
using namespace std;

int main() {
	while (true) {
		int N, M;
		cin >> N >> M;
		if (N == 0 && M == 0) {
			break;
		}
		vector<int> S(N), D(M);
		for (int i = 0; i < N; i++) {
			cin >> S[i];
		}
		for (int i = 0; i < M; i++) {
			cin >> D[i];
		}
		const int INF = 2012345678;
		vector<int> dp(1 << N, INF);
		dp[0] = 0;
		for (int i = 0; i < (1 << N); i++) {
			int cr = 0;
			for (int j = 0; j < N; j++) {
				cr += S[j] * ((i >> j) & 1);
			}
			for (int j = 0; j < N; j++) {
				if (((i >> j) & 1) == 1) {
					int cl = cr - S[j];
					int delta = 0;
					for (int k = 0; k < M; k++) {
						if (cl < D[k] && D[k] <= cr) {
							delta += min(D[k] - cl, cr - D[k]);
						}
					}
					dp[i] = min(dp[i], dp[i ^ (1 << j)] + delta);
				}
			}
		}
		int total = 0;
		for (int i = 0; i < N; i++) {
			total += S[i];
		}
		int finals = 0;
		for (int i = 0; i < M; i++) {
			if (D[i] > total) {
				finals += D[i] - total;
			}
		}
		int answer = dp[(1 << N) - 1] + finals;
		cout << answer << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 350
memory_kb: 3548
final_rank: 7