Problem:
Balance Scale
You, an experimental chemist, have a balance scale and a kit of
    weights for measuring weights of powder chemicals.
For work efficiency, a single use of the balance scale should be
    enough for measurement of each amount.  You can use any number of
    weights at a time, placing them either on the balance plate
    opposite to the chemical or on the same plate with the chemical.
    For example, if you have two weights of 2 and 9 units, you can
    measure out not only 2 and 9 units of the chemical, but also 11 units
    by placing both on the plate opposite to the chemical (Fig. C-1
    left), and 7 units by placing one of them on the plate with the
    chemical (Fig. C-1 right).  These are the only amounts that can be
    measured out efficiently.
Fig. C-1 Measuring 11 and 7 units of chemical
You have at hand a list of amounts of chemicals to measure today.
    The weight kit already at hand, however, may not be enough to
    efficiently measure all the amounts in the measurement list.  If
    not, you can purchase one single new weight to supplement the kit,
    but, as heavier weights are more expensive, you'd like to do with
    the lightest possible.
Note that, although weights of arbitrary positive masses are in
    the market, none with negative masses can be found.
Input
The input consists of at most 100 datasets, each in the following format.
n m
a
1
a
2
...
a
n
w
1
w
2
...
w
m
The first line of a dataset has
n
and
m
,
    the number of amounts in the measurement list and
    the number of weights in the weight kit at hand, respectively.
    They are integers separated by a space
    satisfying 1 ≤
n
≤ 100 and 1 ≤
m
≤ 10.
The next line has the
n
amounts in the measurement list,
a
1
through
a
n
,
separated by spaces.
    Each of
a
i
is an integer
    satisfying 1 ≤
a
i
≤ 10
9
,
    and
a
i
≠
a
j
holds for
i
≠
j
.
The third and final line of a dataset has the list of the masses
    of the
m
weights at hand,
w
1
through
w
m
,
separated by spaces.
    Each of
w
j
is an integer,
    satisfying 1 ≤
w
j
≤ 10
8
.
    Two or more weights may have the same mass.
The end of the input is indicated by a line containing two zeros.
Output
For each dataset, output a single line containing an integer
    specified as follows.
If all the amounts in the measurement list can be measured out
	without any additional weights,
0
.
If adding one more weight will make all the amounts in the
	measurement list measurable, the mass of the lightest among
	such weights.  The weight added may be heavier than
	10
8
units.
If adding one more weight is never enough to measure out all
	the amounts in the measurement list,
-1
.
Sample Input
4 2
9 2 7 11
2 9
6 2
7 3 6 12 16 9
2 9
5 2
7 3 6 12 17
2 9
7 5
15 21 33 48 51 75 111
36 54 57 93 113
0 0
Output for the Sample Input
0
5
-1
5

Submitted solutions:

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

typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;
#define all(x) x.begin(), x.end()
const char nl = '\n';
const int N =1e5+1;
const int INF = 1e9+7;
const ll LINF = 1e18+7;

const int dr[] = {-1,0,1,0}, dc[] = {0,1,0,-1};
void setIO(string);
int n,m;
ll a[N], b[N];
void recur(int i, ll sum, unordered_set<ll>& sums) {
    if(i == m) {
        if(sum >= 0) sums.insert(sum);
        return;
    }
    recur(i+1, sum, sums);
    recur(i+1, sum + b[i], sums);
    recur(i+1, sum - b[i], sums);
}
void solve(){
    
    cin>>n>>m;
    while(n != 0 || m != 0) {
        for(int i = 0; i < n; i++) {
            cin>>a[i];
        }
        for(int j = 0; j < m; j++) {
            cin>>b[j];
        }
        unordered_set<ll> sums;
        recur(0,0ll,sums);

        unordered_set<ll> save;
        int need = 0;
        for(int i = 0; i < n; i++) {
            if(sums.count(a[i])) continue;
            if(!save.empty()) continue;
            need++;
            for(auto &x : sums) {
                save.insert(llabs(x - a[i])); 
                save.insert(x + a[i]);
            }
        }

        if(need == 0) {
            cout << 0;
        } else {
            ll weight = LLONG_MAX;
            //save.insert(0ll);
            for(auto &x : save) {
                bool ok = true;
                for(int i = 0; i < n; i++) {
                    if(sums.count(a[i]) || sums.count(a[i] + x) || sums.count(llabs(a[i] - x))) continue;
                    ok = false;
                }
                if(ok) {
                    weight = min(weight, x);
                }
            }
            cout << (weight == LLONG_MAX ? -1 : weight);
        }
        cout << nl;
        cin>>n>>m;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;

    //setIO("");
    //cin>>t;
    while(t--)solve();

    return 0;
}

void setIO(string s) {
    (void)!freopen((s + ".in").c_str(), "r", stdin);
    (void)!freopen((s + ".out").c_str(), "w", stdout);
}
accuracy: 1
time_ms: 2220
memory_kb: 7652
final_rank: 8

code_snippet: #include <bits/stdc++.h>
#define zpw                    \
  ios::sync_with_stdio(false); \
  cin.tie(NULL);               \
  cout.tie(NULL)

using namespace std;

typedef long long ll;

int a[100 + 10];
int w[100 + 10];
vector<int> vt;
vector<int> st[110];

int main() {
  zpw;
  int n, m;
  // freopen("in.txt", "r", stdin);
  while (cin >> n >> m, (n || m)) {
    vt.clear();
    for (int i = 0; i < 110; i++) {
      st[i].clear();
    }
    for (int i = 0; i < n; i++) {
      cin >> a[i];
    }
    for (int i = 0; i < m; i++) {
      cin >> w[i];
    }
    int tot = pow(3, m);
    int we[tot + 10];
    for (int i = 0; i < tot; i++) {
      int t = i;
      int num = 0;
      for (int j = 0; j < m; j++) {
        if (t % 3 == 1) {
          num += w[j];
        } else if (t % 3 == 2) {
          num -= w[j];
        }
        t /= 3;
      }
      we[i] = num;
    }
    for (int i = 0; i < n; i++) {
      int flag = 0;
      for (int j = 0; j < tot; j++) {
        if (a[i] == abs(we[j])) {
          flag = 1;
          break;
        }
      }
      if (!flag) {
        vt.push_back(i);
        st[i].push_back(a[i]);
      }
    }
    if (vt.empty()) {
      cout << 0 << endl;
      continue;
    }
    for (int i = 0; i < vt.size(); i++) {
      int u = vt[i];
      for (int j = 0; j < tot; j++) {
        st[u].push_back(abs(we[j] - a[u]));
      }
      sort(st[u].begin(), st[u].end());
      int num = unique(st[u].begin(), st[u].end()) - st[u].begin();
      st[u].resize(num);
    }
    int s = vt[0];
    int ans = -1;
    for (int i = 0; i < st[s].size(); i++) {
      int flag = 1;
      for (int j = 1; j < vt.size(); j++) {
        int u = vt[j];
        vector<int>::iterator it =
            lower_bound(st[u].begin(), st[u].end(), st[s][i]);
        if (it == st[u].end() || *it != st[s][i]) {
          flag = 0;
          break;
        }
      }
      if (flag) {
        ans = st[s][i];
        break;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 1560
memory_kb: 24148
final_rank: 7

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

void solve(int n, int m) {
    vector<ll> a(n), w(m);
    ll wsm = 0;
    ll amn = 1ll << 60;
    for (auto &i: a) {
      cin >> i;
      amn = min(amn, i);
    }
    for (auto &i: w) {
      cin >> i;
      wsm += i;
    }
    vector<ll> st;
    st.push_back(0);
    for (int i = 0; i < m; i++) {
        wsm -= w[i];
        vector<ll> nst;
        for (auto j: st) {
            nst.push_back(j);
            nst.push_back(j + w[i]);
            nst.push_back(j - w[i]);
        }
        sort(nst.begin(), nst.end());
        nst.erase(unique(nst.begin(), nst.end()), nst.end());
        swap(st, nst);
    }
    vector<ll> vote;
    int ok = 0;
    bool first = true;
    for (const auto &i: a) {
        if (*lower_bound(st.begin(), st.end(), i) == i) {
            ok++;
            continue;
        }
        if (first) {
            first = false;
            for (const auto &j: st) {
                vote.push_back(abs(i - j));
            }
            sort(vote.begin(), vote.end());
            vote.erase(unique(vote.begin(), vote.end()), vote.end());
        }
        else {
            vector<ll> nvote;
            for (const auto &j: st) {
                nvote.push_back(abs(i - j));
            }
            sort(nvote.begin(), nvote.end());
            nvote.erase(unique(nvote.begin(), nvote.end()), nvote.end());
            vector<ll> tmp;
            for (const auto &j: vote) {
                if (*lower_bound(nvote.begin(), nvote.end(), j) == j) tmp.push_back(j);
            }
            swap(vote, tmp);
        }
    }
    if (ok == n) cout << "0\n";
    else {
        for (const auto &pa: vote) {
            cout << pa << "\n";
            return;
        }
        cout << "-1\n";
    }
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(0);
    while (true) {
        int n, m;
        cin >> n >> m;
        if (n == 0) return 0;
        solve(n, m);
    }
}
accuracy: 1
time_ms: 890
memory_kb: 5272
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
struct Init {
  Init() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout << setprecision(13);
  }
} init;

using ll = long long;
using ull = unsigned long long;
using VLL = vector<ll>;
using VVLL = vector<VLL>;
using PLL = pair<ll, ll>;
using VS = vector<string>;

#define rep(i, n) for (int i = 0; i < int(n); ++i)
#define FOR(i, a, b) for (int i = int(a); i < int(b); ++i)
#define all(x) (x).begin(), (x).end()
#define rall(x) x.rbegin(), x.rend()

const double PI = 3.141592653589793238;
const int INF = 1073741823;
const ll INFLL = 1LL << 60;
const string ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string abc = "abcdefghijklmnopqrstuvwxyz";
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
  for (int i = 0; i < (int)v.size(); i++)
    os << v[i] << (i + 1 != (int)v.size() ? " " : "");
  return os;
}
template <typename T>
istream& operator>>(istream& is, vector<T>& v) {
  for (T& in : v)
    is >> in;
  return is;
}
void print() {
  cout << '\n';
}
template <typename T>
void print(const T& t) {
  cout << t << '\n';
}
template <typename Head, typename... Tail>
void print(const Head& head, const Tail&... tail) {
  cout << head << ' ';
  print(tail...);
}
template <typename T1, typename T2>
inline bool chmax(T1& a, T2 b) {
  bool compare = a < b;
  if (compare)
    a = b;
  return compare;
}
template <typename T1, typename T2>
inline bool chmin(T1& a, T2 b) {
  bool compare = a > b;
  if (compare)
    a = b;
  return compare;
}

int main() {
  while (true) {
    int n, m;
    cin >> n >> m;
    if (n == 0 && m == 0)
      return 0;

    VLL a(n);
    VLL w(m);
    cin >> a >> w;

    set<ll> hakareru;
    for (auto i : w)
      hakareru.insert(i);
    for (int i = 0; i < (1 << m); i++) {
      for (int j = 0; j < (1 << m); j++) {
        if ((i & j) != 0)
          continue;
        ll weight = 0;
        rep(z, m) {
          if (i & (1 << z))
            weight += w[z];
          if (j & (1 << z))
            weight -= w[z];
        }
        if (weight <= 0)
          continue;

        hakareru.insert(weight);
        if (weight == 48) {
          print(i, j);
        }
      }
    }
    set<ll> hakarenai;
    rep(i, n) {
      if (!hakareru.count(a[i])) {
        hakarenai.insert(a[i]);
      }
    }
    if (hakarenai.empty()) {
      print(0);
      continue;
    }

    vector<set<ll>> e(hakarenai.size());
    {
      int i = 0;
      for (auto c : hakarenai) {
        for (auto d : hakareru) {
          e[i].insert(c + d);
          e[i].insert(abs(c - d));
          e[i].insert(c);
        }
        i++;
      }
    }

    if (hakarenai.size() == 1) {
      for (auto hh : e[0]) {
        print(hh);
        break;
      }
      continue;
    }
    bool flag = false;
    for (auto x : e[0]) {
      FOR(i, 1, hakarenai.size()) {
        if (!e[i].count(x)) {
          break;
        }
        if (i == hakarenai.size() - 1) {
          flag = true;
          print(x);
          break;
        }
      }
      if (flag)
        break;
    }
    if (!flag) {
      print(-1);
    }
  }
}
accuracy: 1
time_ms: 5200
memory_kb: 234448
final_rank: 18

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

void solve(ll n, ll m){
    vector<ll> a(n),b(m);
    for (int i = 0; i < n; i++)cin >> a[i];
    for (int i = 0; i < m; i++)cin >> b[i];

    set<ll> c;
    for (int i = 0; i < m; i++){
        set<ll> d;
        d.insert(b[i]);
        for (auto p: c){
            d.insert(p);
            d.insert(abs(p-b[i]));
            d.insert(abs(p+b[i]));
        }
        swap(c,d);
    }

    vector<ll> no;
    for (int i = 0; i < n; i++)if (!c.count(a[i]))no.push_back(a[i]);
    if (no.size() == 0){
        cout << 0 << endl;
        return;
    }

    vector<set<ll>> diff(no.size());
    for (int i = 0; i < no.size(); i++){
        for (auto p: c){
            diff[i].insert(no[i]);
            diff[i].insert(p+no[i]);
            diff[i].insert(abs(p-no[i]));
        }
    }
    int idx = 0;
    for (int i = 1; i < no.size(); i++)if (diff[idx].size() > diff[i].size())idx = i;

    for (auto p: diff[idx]){
        bool jud = true;
        for (int i = 0; i < no.size(); i++){
            if (i == idx)continue;

            if (!diff[i].count(p)){
                jud = false;
                break;
            }
        }
        if (jud){
            cout << p << endl;
            return;
        }
    }
    cout << -1 << endl;
}

int main(){
    ll n,m;cin >> n >> m;
    while(n){
        solve(n,m);
        cin >> n >> m;
    }
}
accuracy: 1
time_ms: 5150
memory_kb: 234512
final_rank: 17

code_snippet: # include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
const double pi = acos(-1);
template<class T>constexpr T inf() { return ::std::numeric_limits<T>::max(); }
template<class T>constexpr T hinf() { return inf<T>() / 2; }
template <typename T_char>T_char TL(T_char cX) { return tolower(cX); }
template <typename T_char>T_char TU(T_char cX) { return toupper(cX); }
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; }
int popcnt(unsigned long long n) { int cnt = 0; for (int i = 0; i < 64; i++)if ((n >> i) & 1)cnt++; return cnt; }
int d_sum(ll n) { int ret = 0; while (n > 0) { ret += n % 10; n /= 10; }return ret; }
int d_cnt(ll n) { int ret = 0; while (n > 0) { ret++; n /= 10; }return ret; }
ll gcd(ll a, ll b) { if (b == 0)return a; return gcd(b, a%b); };
ll lcm(ll a, ll b) { ll g = gcd(a, b); return a / g*b; };
ll MOD(ll x, ll m){return (x%m+m)%m; }
ll FLOOR(ll x, ll m) {ll r = (x%m+m)%m; return (x-r)/m; }
template<class T> using dijk = priority_queue<T, vector<T>, greater<T>>;
# define all(qpqpq)           (qpqpq).begin(),(qpqpq).end()
# define UNIQUE(wpwpw)        (wpwpw).erase(unique(all((wpwpw))),(wpwpw).end())
# define LOWER(epepe)         transform(all((epepe)),(epepe).begin(),TL<char>)
# define UPPER(rprpr)         transform(all((rprpr)),(rprpr).begin(),TU<char>)
# define rep(i,upupu)         for(ll i = 0, i##_len = (upupu);(i) < (i##_len);(i)++)
# define reps(i,opopo)        for(ll i = 1, i##_len = (opopo);(i) <= (i##_len);(i)++)
# define len(x)                ((ll)(x).size())
# define bit(n)               (1LL << (n))
# define pb push_back
# define eb emplace_back
# define exists(c, e)         ((c).find(e) != (c).end())

struct INIT{
	INIT(){
		std::ios::sync_with_stdio(false);
		std::cin.tie(0);
		cout << fixed << setprecision(20);
	}
}INIT;

namespace mmrz {
	void solve();
}

int main(){
	mmrz::solve();
}
#define debug(...) (static_cast<void>(0))

using namespace mmrz;

using vll=vector<ll>;
using vvll = vector<vector<ll>>;
using ull = unsigned long long;
using lll = __int128;
#define per(i,n) for(ll i=n-1;i>=0;--i)
#define rep2(i,a,n) for (ll i=a;i<n;++i)
#define per2(i,a,n) for (ll i=a;i>=n;--i)

// [BEGIN] template の include

int SOLVE(){
	int n, m;
	cin >> n >> m;
	if(n == 0 && m == 0)return 1;
	vector<int> a(n), w(m);
	for(auto &x : a)cin >> x;
	for(auto &x : w)cin >> x;
	
	vector<int> valid_weights;
	auto dfs = [&](auto f, int idx, int c) -> void {
		if(idx == m){
			valid_weights.eb(c);
			return;
		}
		for(int d = -1;d <= 1;d++){
			c += w[idx]*d;
			f(f, idx+1, c);
			c -= w[idx]*d;
		}
	};
	dfs(dfs, 0, 0);
	sort(all(valid_weights));
	UNIQUE(valid_weights);
	
	{
		vector<int> na;
		for(auto &x : a){
			auto it = lower_bound(all(valid_weights), x);
			if(it != valid_weights.end() && *it == x)continue;
			na.eb(x);
		}
		a = na;
	}
	if(a.empty()){
		cout << "0\n";
		return 0;
	}
	int ans = hinf<int>();
	for(auto x : valid_weights){
		int cand = abs(a[0]-x);
		bool flg = true;
		for(auto sa : a){
			auto it_l = lower_bound(all(valid_weights), abs(sa-cand));
			if(it_l != valid_weights.end() && *it_l == abs(sa-cand))continue;
			auto it_r = lower_bound(all(valid_weights), sa+cand);
			if(it_r != valid_weights.end() && *it_r == sa+cand)continue;
			flg = false;
			break;
		}
		if(flg)chmin(ans, cand);
	}

	cout << (ans == hinf<int>() ? -1 : ans) << '\n';
	return 0;
}

void mmrz::solve(){
	while(!SOLVE());
}
accuracy: 1
time_ms: 130
memory_kb: 3820
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using P = pair<int, int>;
using PP = pair<int, P>;
using PLL = pair<ll, ll>;
using PPLL = pair<ll, PLL>;
#define rep(i, n) for(ll i = 0; i < n; ++i)
#define rrep(i, n) for(ll i = n - 1; i >= 0; --i)
#define loop(i, a, b) for(ll i = a; i <= b; ++i)
#define all(v) v.begin(), v.end()
#define nC2(n) n * (n - 1) / 2
constexpr ll INF = 9009009009009009009LL;
constexpr int INF32 = 2002002002;
constexpr ll MOD = 998244353;
constexpr ll MOD107 = 1000000007;

// Linear Algebra ////////////////////////////////////////////////
const double Rad2Deg = 180.0 / M_PI;
const double Deg2Rad = M_PI / 180.0;
//////////////////////////////////////////////////////////////////

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

template <class T>
inline bool chmax(T &a, const T &b) {
	if (a < b) {
		a = b;
		return true;
	}
	return false;
}
template <class T>
inline bool chmin(T &a, const T &b) {
	if (a > b) {
		a = b;
		return true;
	}
	return false;
}

template <typename Container,
          typename = std::enable_if_t<
              !std::is_same_v<Container, std::string> &&
              std::is_convertible_v<decltype(std::declval<Container>().begin()),
                                    typename Container::iterator>>>
ostream &operator<<(ostream &os, const Container &container) {
    auto it = container.begin();
    auto end = container.end();

    if (it != end) {
        os << *it;
        ++it;
    }
	for (; it != end; ++it) {
		os << " " << *it;
	}
    return os;
}
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    for (size_t i = 0; i < v.size(); ++i) {
        os << v[i];
        if (i != v.size() - 1) os << " ";
    }
    return os;
}
template <typename T>
ostream& operator<<(ostream& os, const vector<vector<T>>& vv) {
	for (size_t i = 0; i < vv.size(); ++i) {
		os << vv[i];
		if (i != vv.size() - 1) os << "\n";
    }
    return os;
}
template <typename T>
istream& operator>>(istream& is, vector<T>& v) {
	assert(v.size() > 0);
	for (size_t i = 0; i < v.size(); ++i) is >> v[i];
	return is;
}
template <typename T>
istream& operator>>(istream& is, vector<vector<T>>& vv) {
	assert(vv.size() > 0);
	for (size_t i = 0; i < vv.size(); ++i) is >> vv[i];
	return is;
}

struct phash {
	template<class T1, class T2>
    inline size_t operator()(const pair<T1, T2> & p) const {
        auto h1 = hash<T1>()(p.first);
        auto h2 = hash<T2>()(p.second);

		size_t seed = h1 + h2; 
		h1 = ((h1 >> 16) ^ h1) * 0x45d9f3b;
        h1 = ((h1 >> 16) ^ h1) * 0x45d9f3b;
        h1 = (h1 >> 16) ^ h1;
        seed ^= h1 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
		h2 = ((h2 >> 16) ^ h2) * 0x45d9f3b;
        h2 = ((h2 >> 16) ^ h2) * 0x45d9f3b;
        h2 = (h2 >> 16) ^ h2;
        seed ^= h2 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
        return seed;
    }
};





int solve() {
	ll n, m; cin >> n >> m;
	if (n == 0 && m == 0) return 1;
	vll a(n), w(m);
	cin >> a;
	cin >> w;

	set<ll> needs;
	rep(i, n) needs.insert(a[i]);

	set<ll> can_weights;
	auto dfs = [&](auto self, ll l, ll r, ll i) -> void {
		can_weights.insert(abs(l - r));
		needs.erase(abs(l - r));
		if (m <= i) return;

		self(self, l, r, i + 1);
		self(self, l + w[i], r, i + 1);
		self(self, l, r + w[i], i + 1);
	};
	dfs(dfs, 0, 0, 0);

	if (needs.size() == 0) {
		cout << 0 << "\n";
		return 0;
	}

	set<ll> ok;
	auto it = needs.begin();
	for (ll weight : can_weights) {
		ok.insert(abs(*it - weight));
		ok.insert(*it + weight);
	}
	it++;
	for (;it != needs.end(); it++) {
		set<ll> oldok;
		swap(ok, oldok);
		for (ll weight : can_weights) {
			ll diff = abs(*it - weight);
			ll sum = *it + weight;
			if (oldok.count(diff)) ok.insert(diff);
			if (oldok.count(sum)) ok.insert(sum);
		}
	}

	if (ok.size() == 0) {
		cout << -1 << "\n";
	}
	else {
		cout << *ok.begin() << "\n";
	}

	return 0;
}

int main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);

	while (!solve()) { }

	return 0;
}
accuracy: 1
time_ms: 650
memory_kb: 9416
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using a2 = array<ll, 2>;
using a3 = array<ll, 3>;

template <typename A> void chmin(A &l, const A &r) {
    if(r < l)
        l = r;
}
template <typename A> void chmax(A &l, const A &r) {
    if(l < r)
        l = r;
}

ll mod = 998244353;

void init() {}

ll n, m;
vector<ll> a, w;
void input() {
    cin >> n >> m;
    a.resize(n);
    w.resize(m);
    for(auto &x : a)
        cin >> x;
    for(auto &x : w)
        cin >> x;
}
void solve() {
    unordered_set<ll> sh;
    ll san = 1;
    for(int i = 0; i < m; i++) {
        san *= 3;
    }
    for(int i = 0; i < san; i++) {
        ll sum = 0;
        ll t = 1;
        for(int j = 0; j < m; j++) {
            if((i / t) % 3 == 1) {
                sum += w[j];
            } else if((i / t) % 3 == 2) {
                sum -= w[j];
            }
            t *= 3;
        }
        sh.insert(sum);
    }

    for(int i = 0; i < n; i++) {
        if(sh.count(a[i]) == 0) {
            ll ans = 1e18;
            for(auto &x : sh) {
                ll add = a[i] - x;
                if(add < 0)
                    continue;
                bool ok = true;
                for(int j = 0; j < n; j++) {
                    if(sh.count(a[j]) == 0 && sh.count(a[j] - add) == 0 &&
                       sh.count(a[j] + add) == 0)
                        ok = false;
                }
                if(ok) {
                    ans = min(add,ans);
                }
            }
            for(auto &x : sh) {
                ll add = x - a[i];
                if(add < 0)
                    continue;
                bool ok = true;
                for(int j = 0; j < n; j++) {
                    if(sh.count(a[j]) == 0 && sh.count(a[j] - add) == 0 &&
                       sh.count(a[j] + add) == 0)
                        ok = false;
                }
                if(ok) {
                    ans = min(add,ans);
                }
            }

            cout << (ans == 1e18 ? -1 : ans) << endl;
            return;
        }
    }

    cout << 0 << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    // init();
    while(1) {
        input();
        if(n == 0)
            break;
        solve();
    }

    return 0;
}
accuracy: 1
time_ms: 2280
memory_kb: 6148
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using a2 = array<ll, 2>;
using a3 = array<ll, 3>;

template <typename A> void chmin(A &l, const A &r) {
    if(r < l)
        l = r;
}
template <typename A> void chmax(A &l, const A &r) {
    if(l < r)
        l = r;
}

ll mod = 998244353;

void init() {}

ll n, m;
vector<ll> a, w;
void input() {
    cin >> n >> m;
    a.resize(n);
    w.resize(m);
    for(auto &x : a)
        cin >> x;
    for(auto &x : w)
        cin >> x;
}
void solve() {
    set<ll> sh;
    ll san = 1;
    for(int i = 0; i < m; i++) {
        san *= 3;
    }
    for(int i = 0; i < san; i++) {
        ll sum = 0;
        ll t = 1;
        for(int j = 0; j < m; j++) {
            if((i / t) % 3 == 1) {
                sum += w[j];
            } else if((i / t) % 3 == 2) {
                sum -= w[j];
            }
            t *= 3;
        }
        sh.insert(sum);
    }

    for(int i = 0; i < n; i++) {
        if(sh.count(a[i]) == 0) {
            ll ans = 1e18;
            for(auto &x : sh) {
                ll add = a[i] - x;
                if(add < 0)
                    continue;
                bool ok = true;
                for(int j = 0; j < n; j++) {
                    if(sh.count(a[j]) == 0 && sh.count(a[j] - add) == 0 &&
                       sh.count(a[j] + add) == 0)
                        ok = false;
                }
                if(ok) {
                    ans = min(add,ans);
                }
            }
            for(auto &x : sh) {
                ll add = x - a[i];
                if(add < 0)
                    continue;
                bool ok = true;
                for(int j = 0; j < n; j++) {
                    if(sh.count(a[j]) == 0 && sh.count(a[j] - add) == 0 &&
                       sh.count(a[j] + add) == 0)
                        ok = false;
                }
                if(ok) {
                    ans = min(add,ans);
                }
            }

            cout << (ans == 1e18 ? -1 : ans) << endl;
            return;
        }
    }

    cout << 0 << endl;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    // init();
    while(1) {
        input();
        if(n == 0)
            break;
        solve();
    }

    return 0;
}
accuracy: 1
time_ms: 7290
memory_kb: 6116
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define fr(i,n) for(long long i=0; i<(n); i++)
using ll = long long;

int main() {
    vector<ll> ans;
    while(true){
        ll n,m;
        cin >> n >> m;
        if(n==0) break;
        vector<set<ll>> buy(n);
        unordered_set<ll> possible;
        vector<ll> a(n),w(m),inpossible;
        fr(i,n) cin >> a[i];
        fr(i,m) cin >> w[i];
        possible.insert(0);
        fr(i,m){
            auto itr = possible.begin();
            queue<ll> q;
            fr(j,possible.size()){
                q.push(*itr+w[i]);
                q.push(abs(*itr-w[i]));
                itr++;
            }
            while(!q.empty()){
                possible.insert(q.front());
                q.pop();
            }
        }
        fr(i,n){
            if(possible.count(a[i])) continue;
            inpossible.push_back(i);
            auto itr = possible.begin();
            fr(j,possible.size()){
                buy[i].insert(a[i]+*itr);
                buy[i].insert(abs(a[i]-*itr));
                itr++;
            }
        }
        if(inpossible.size() == 0) ans.push_back(0);
        else{
            set<ll> common = buy[inpossible[0]];
            for(ll i=1; i<inpossible.size(); i++){
                set<ll> tmp;
                set_intersection(common.begin(),common.end(),buy[inpossible[i]].begin(),buy[inpossible[i]].end(),inserter(tmp, tmp.begin()));
                common = tmp;
            }
            if(common.size()==0) ans.push_back(-1);
            else ans.push_back(*common.begin());
        }
    }
    fr(i,ans.size()) cout << ans[i] << endl;
}
accuracy: 1
time_ms: 6680
memory_kb: 237052
final_rank: 19

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

using ll = long long;
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
typedef pair<int, int> pii;
typedef vector<int> vi;
template <class T>
inline bool chmin(T &a, T b) {
  return ((a > b) ? (a = b, 1) : (0));
}
template <class T>
inline bool chmax(T &a, T b) {
  return ((a < b) ? (a = b, 1) : (0));
}

int main() {
  while (solve());
  return 0;
}

bool solve() {
  int N, M;
  cin >> N >> M;
  if (N==0) return 0;
  vector<ll>A(N),W(M);
  for(auto &a:A)cin>>a;
  for(auto &w:W)cin>>w;
  
  //追加しなくてもいい薬品量を求める
  set<ll>S;
  S.insert(0);
  rep(i,0,M){
    set<ll>nS;
    for(auto s:S){
      nS.insert(s+W[i]);      
      nS.insert(s-W[i]);      
      nS.insert(s);
    }
    S=nS;
  }

  //Aからそのままでいいものを削除
  for(int i=N-1;i>=0;i--){
    if(S.count(A[i])){
      A.erase(A.begin()+i);
    }
  }

  //0個になったら
  if(sz(A)==0){
    cout<<0<<endl;
    return 1;
  }

  //すべてが取れるようなものがあるか？
  //候補としてAの先頭要素に追加して量れるようになる分銅の量
  vector<ll>candidates;
  for(auto s:S){
    candidates.push_back(abs(A[0]-s));
  }

  
  //最小から見ていきいい感じのとる
  sort(all(candidates));
  for(auto c:candidates){
    bool f=true;
    for(auto a:A){
      if(!(S.count(a-c) || S.count(a+c))){
        f=false;
        break;
      }
    }
    if(f){
      cout<<c<<endl;
      return 1;
    }
  }  
  cout<<-1<<endl;
  return 1;
}
accuracy: 1
time_ms: 190
memory_kb: 9344
final_rank: 3

code_snippet: //~~~~~~~~~~

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

using ll = long long;
using ld = long double;

#if !defined(ONLINE_JUDGE)
#define _GLIBCXX_DEBUG
#endif

#define rrep(i, s, n) for (ll i = s; i < (n); i++)
#define rep(i, n) rrep(i, 0, n)
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()

//~~~~~~~~~~

template <class ...C>
void in(C &...v) { (cin >> ... >> v); }

template <class C>
void out_single(const C& v) { cout << v; }

void out_single(const char& v) { cout << v; }

template <class ...C>
void out(C&&...v) { (out_single(v), ...); }

template <class C>
void err_single(const C& v) { cerr << v; }

void err_single(const char& v) { cerr << v; }

template <class ...C>
void err(C&&...v) { (err_single(v), ...); }

//~~~~~~~~~~

template <class C>
bool chmax(C &a, const C b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

template <class C>
bool chmin(C &a, const C b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

template<class C1, class C2>
istream& operator>>(istream& is, pair<C1, C2>& p) {
    return is >> p.first >> p.second;
}

bool is_grid(int h, int w, int y, int x) {
    return (0 <= y && y < h && 0 <= x && x < w);
}

//~~~~~~~~~~

ll llpow(ll x, ll y) {
    ll res = 1;
    while (y--) res *= x;
    return res;
}

//~~~~~~~~~~

int main() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);

    while (true) {
        int n, m; in(n, m);
        if (n == 0 && m == 0) break;

        vector<int> A(n), B(m);
        rep (i, n) in(A[i]);
        rep (i, m) in(B[i]);

        // 現時点で作れる数の全列挙
        set<int> cur_canmake;
        rep (bit, llpow(3, m)) {  // 59049回
            int left_ = 0, right_ = 0;
            rep (i, m) {
                if (bit / llpow(3, i) % 3 == 0) {
                    left_ += B[i];
                } else if (bit / llpow(3, i) % 3 == 1) {
                    right_ += B[i];
                }
            }

            cur_canmake.insert(abs(left_ - right_));
        }

        // // この分銅があれば作れるよ！リスト
        // // もしそのidx番目のsetに0があるなら既に作れる！
        // vector<set<int>> G(n);
        // set<int> test;
        // rep (idx, n) { // 100回
        //     for (int i : cur_canmake) { // 59049回
        //         G[idx].insert(abs(A[idx] - i));
        //         G[idx].insert(A[idx] + i);
        //         test.insert(abs(A[idx] - i));
        //         test.insert(A[idx] + i);
        //     }
        // }

        // // res を探す
        // // 全部に0があったら？ -> 範囲for分の最初で落とせる
        // // 全部探してもなかったら？ -> そのままres出力
        // int res = -1;
        // bool ok = false;
        // for (int i : test) { // 約100000回
        //     rep (j, n) { // 100回
        //         if (!G[j].count(0) && !G[j].count(i)) break;

        //         if (j == n - 1) {
        //             res = i;
        //             ok = true;
        //             break;
        //         }
        //     }
        //     if (ok) break;
        // }

        // この分銅があれば作れるよ！リスト
        // もしそのidx番目のsetに0があるなら既に作れる！
        vector<set<int>> G(n);
        rep (idx, n) { // 100回
            for (int i : cur_canmake) { // 59049回
                G[idx].insert(abs(A[idx] - i));
                G[idx].insert(A[idx] + i);
            }
        }

        // res を探す
        // 全部に0があったら？ -> 範囲for分の最初で落とせる
        // 全部探してもなかったら？ -> そのままres出力
        int res = -1;
        bool ok = false;
        rep (i, n) {
            for (int j : G[i]) {
                rep (k, n) {
                    if (i == k) continue;

                    if (!G[k].count(0) && !G[k].count(j)) {
                        break;
                    }

                    if (k == n - 1) {
                        res = j;
                        ok = true;
                        break;
                    }
                }
                if (ok) break;
            }
            if (ok) break;
        }

        out(res, '\n');

        /*
        6 2
        7 3 6 12 16 9
        2 9

        3 6 7 9 12 16
        2 7 9 11

        - 1 4 5  7 10 14
        + 5 8 9 11 14 18
        - 4 1 0  2  5  9
        - 6 3 2  0  3  7
        - 8 5 4  2  1  5
        
        */
    }

    return 0;
}
accuracy: 1
time_ms: 7930
memory_kb: 250972
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
  #include "settings/debug.cpp"
#else
  #define Debug(...) void(0)
#endif
#define rep(i, n) for (int i = 0; i < (n); ++i)
using ll = long long;
using ull = unsigned long long;

inline void solve() {
  int n, m;
  cin >> n >> m;
  if (n + m == 0) exit(0);
  vector<ll> a(n);
  rep(i, n) cin >> a[i];
  vector<ll> w(m);
  rep(i, m) cin >> w[i];

  set<ll> cand;
  function<void(int, ll)> dfs = [&](int i, ll sum) {
    if (i == m) {
      cand.insert(sum);
      return;
    }
    dfs(i + 1, sum);
    dfs(i + 1, sum + w[i]);
    dfs(i + 1, sum - w[i]);
  };
  dfs(0, 0);

  {
    bool ok = true;
    for (auto x : a) {
      if (!cand.contains(x)) ok = false;
    }
    if (ok) {
      cout << 0 << '\n';
      return;
    }
  }

  set<ll> need;
  bool flg = false;
  for (auto x : a) {
    if (cand.contains(x)) continue;
    if (!flg) {
      flg = true;
      for (auto y : cand) {
        need.insert(x + y);
        need.insert(x - y);
        need.insert(y - x);
      }
    }
    else {
      set<ll> new_need;
      for (auto y : need) {
        if (cand.contains(x + y) || cand.contains(x - y) || cand.contains(y - x)) new_need.insert(y);
      }
      swap(need, new_need);
    }
  }
  if (need.empty()) {
    cout << -1 << '\n';
    return;
  }
  ll ans = 1e18;
  for (auto x : need) {
    if (x <= 0) continue;
    ans = min(ans, x);
  }
  cout << ans << '\n';
}

int main() {
  cin.tie(nullptr)->sync_with_stdio(false);
  while (true) solve();
  return 0;
}
accuracy: 1
time_ms: 590
memory_kb: 12672
final_rank: 5

code_snippet: // #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
// #include <atcoder/all>
using namespace std;
// using namespace atcoder;
#define rep(i, a, b) for(int i = (a); i < (b); i++) // [a, b)を昇順に
#define drep(i, a, b) for(int i = (b) - 1; i >= a; i--) // [a, b)を降順に
#define all(v) v.begin(), v.end() // 昇順sortに
#define rall(v) v.rbegin(), v.rend() // 降順sortに
#define sz(x) (int)(x).size()
#define decimal(n) cout << fixed << setprecision(n);
#define debug(x) cerr << #x << " = " << x << endl;
#define Yes cout << "Yes" << endl;
#define No cout << "No" << endl;
#define yesno(condition) { if (condition) cout << "Yes" << endl; else cout << "No" << endl; }
using vi = vector<int>; using vvi = vector<vi>; using vs = vector<string>;
using ll = long long; using vl = vector<ll>; using vvl = vector<vl>; using vvvl = vector<vvl>;
using lll = __int128;
// using mint = modint998244353;
const ll MOD = 998244353;
// using mint = modint;
// const ll MOD = 998244353;
// using mint = modint1000000007;
// const ll MOD = 1000000007;
// using vm = vector<mint>; using vvm = vector<vm>; using vvvm = vector<vvm>;
using P = pair<ll, ll>; using T = tuple<ll, ll, ll>;
using vc = vector<char>;
const ll MAX = 5'000'009; const ll llINF = 2e18;
const int intINF = 2e9; const long double pi = acos(-1);
ll di[] = {0, -1, 0, 1, -1, -1, 1, 1};
ll dj[] = {1, 0, -1, 0, 1, -1, -1, 1};
template<class T>bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }
template<class T> using pq = priority_queue<T, vector<T>>; //大きい順
template<class T> using pq_g = priority_queue<T, vector<T>, greater<T>>; //小さい順

bool isin(ll i, ll j, ll n, ll m) { return (0 <= i && i < n && 0 <= j && j < m); }
bool is_multipul_overflow(ll a, ll b, ll c) {
    // a * b > cかを判定する
    if (a == 0 || b == 0) return false;
    return (a <= c / b ? false : true);
}

template<class T, size_t n, size_t idx = 0>
auto make_vec(const size_t (&d)[n], const T& init) noexcept {
    if constexpr (idx < n) return std::vector(d[idx], make_vec<T, n, idx + 1>(d, init));
    else return init;
}
template<class T, size_t n>
auto make_vec(const size_t (&d)[n]) noexcept {
    return make_vec(d, T{});
}
/**
 * Read a vector from input. Set start to 1 if you want it to be 1-indexed.
 */
template<typename T>
vector<T> read_vector(int N, int start = 0) {
    vector<T> v(start + N);
    for (int i = start; i < (int)v.size(); i++) {
        std::cin >> v[i];
    }
    return v;
}

void solve(int &n, int &m) {
    vector<int> a(n), w(m);
    rep(i, 0, n) cin >> a[i];
    rep(i, 0, m) cin >> w[i];

    set<int> s;
    s.insert(0);
    rep(i, 0, m) {
        set<int> nexts;
        for(auto curw : s) {
            rep(c, -1, 2) {
                nexts.insert(curw + c * w[i]);                
            }
        }
        swap(nexts, s);
    }

    bool canbalanced = true;
    rep(i, 0, n) {
        if(!s.count(a[i])) canbalanced = false;
    }

    if(canbalanced) {
        cout << 0 << endl;
        return ;
    }


    int ans = intINF;
    rep(i, 0, n) {
        if(s.count(a[i])) continue;

        for(auto allw : s) {
            int addw = abs(allw - a[i]);
            if(addw < 0) continue;

            bool isok = true;
            rep(j, 0, n) {
                bool isfind = false;
                for(auto cc : {-1, 0, 1}) {
                    if(s.count(a[j] + cc * addw)) isfind = true;
                }

                if(!isfind) {
                    isok = false;
                    break;
                }
            }

            if(isok) chmin(ans, addw);
        }
    }

    cout << (ans == intINF ? -1 : ans) << endl;
}

int main() {
    int n, m;
    while(true) {
        cin >> n >> m;
        if(n == 0 && m == 0) return 0;
        solve(n, m);
    }
}
accuracy: 1
time_ms: 4670
memory_kb: 6984
final_rank: 10

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

void dfs1(int m, long long sum, vector<long long> &W, int M, bool &f) {
    if (m == M) {
        if (sum == 0) {
            f = true;
        }
        return;
    }
    dfs1(m + 1, sum + W[m], W, M, f);
    dfs1(m + 1, sum, W, M, f);
    dfs1(m + 1, sum - W[m], W, M, f);
}

void dfs2(int m, long long sum, vector<long long> &W, int M,
          map<long long, int> &add) {
    if (m == M) {
        add[abs(sum)] = 1;
        return;
    }
    dfs2(m + 1, sum + W[m], W, M, add);
    dfs2(m + 1, sum, W, M, add);
    dfs2(m + 1, sum - W[m], W, M, add);
}

void dfs3(int m, long long sum, vector<long long> &W, int M,
          set<long long> &add) {
    if (m == M) {
        add.insert(abs(sum));
        return;
    }
    dfs3(m + 1, sum + W[m], W, M, add);
    dfs3(m + 1, sum, W, M, add);
    dfs3(m + 1, sum - W[m], W, M, add);
}

void solve() {
    int N, M;
    cin >> N >> M;
    if (N == 0 && M == 0) {
        exit(0);
    }
    vector<long long> A(N), W(M);
    for (int i = 0; i < N; i++) {
        cin >> A[i];
    }
    for (int i = 0; i < M; i++) {
        cin >> W[i];
    }
    vector<int> a;
    for (int i = 0; i < N; i++) {
        bool flag = false;
        dfs1(0, A[i], W, M, flag);
        if (flag == false) {
            a.push_back(A[i]);
        }
    }
    if (a.size() == 0) {
        cout << 0 << endl;
    } else {
        map<long long, int> add;
        dfs2(0, a[0], W, M, add);
        for (int i = 1; i < a.size(); i++) {
            set<long long> addset;
            dfs3(0, a[i], W, M, addset);
            for (long long x : addset) {
                if (add.find(x) != add.end()) {
                    add[x]++;
                }
            }
        }
        for (auto x : add) {
            if (x.second == a.size()) {
                cout << x.first << endl;
                return;
            }
        }
        cout << -1 << endl;
    }
}

int main() {
    while (1) {
        solve();
    }
    return 0;
}
accuracy: 1
time_ms: 6560
memory_kb: 10112
final_rank: 11

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

using namespace std;
using ll = long long;

int main() {
    while (true) {
        int N, M;
        cin >> N >> M;
        if (N == 0 && M == 0) {
            break;
        }

        vector<int> A(N), W(M);
        for (int i = 0; i < N; i++) {
            cin >> A[i];
        }
        for (int i = 0; i < M; i++) {
            cin >> W[i];
        }

        vector<vector<int>> weight(1 << M);
        for (int bit = 0; bit < 1 << M; bit++) {
            vector<int> S;
            for (int i = 0; i < M; i++) {
                if (!(bit & (1 << i))) {
                    S.push_back(W[i]);
                }
            }

            for (int s = 0; s < 1 << S.size(); s++) {
                int wei = 0;
                for (int i = 0; i < S.size(); i++) {
                    if (s & (1 << i)) {
                        wei += S[i];
                    }
                }
                weight[bit].push_back(wei);
            }
            weight[bit].erase(unique(weight[bit].begin(), weight[bit].end()), weight[bit].end());
            ranges::sort(weight[bit]);
        }

        map<int, int> cnt_mp;
        int ng_cnt = 0;
        for (int i = 0; i < N; i++) {
            bool ok = false; // 計測できるか
            vector<int> add; // 計測できない場合、どの重さを追加すればいいか

            for (int bit = 0; bit < (1 << M); bit++) {
                int right_w = 0;
                for (int j = 0; j < M; j++) {
                    if (bit & (1 << j)) {
                        right_w += W[j];
                    }
                }

                for (int weight_i : weight[bit]) {
                    if (right_w == (A[i] + weight_i)) {
                        ok = true;
                    } else if (right_w > (A[i] + weight_i)) {
                        add.push_back(right_w - (A[i] + weight_i));
                    } else {
                        add.push_back((A[i] + weight_i) - right_w);
                    }
                }
            }

            if (!ok) {
                ng_cnt++;
                ranges::sort(add);
                add.erase(unique(add.begin(), add.end()), add.end());
                for (int vi : add) {
                    cnt_mp[vi]++;
                }
            }
        }

        if (ng_cnt == 0) {
            cout << 0 << endl;
        } else {
            int ans = -1;
            for (auto [wei, cnt] : cnt_mp) {
                if (cnt == ng_cnt) {
                    ans = wei;
                    break;
                }
            }
            cout << ans << endl;
        }
    }
}
accuracy: 1
time_ms: 5150
memory_kb: 113536
final_rank: 15

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

using namespace std;
using ll = long long;

constexpr int INF = 2e9;


int main() {
    while (true) {
        int N, M;
        cin >> N >> M;
        if (N == 0 && M == 0) {
            break;
        }

        vector<int> A(N), W(M);
        for (int i = 0; i < N; i++) {
            cin >> A[i];
        }
        for (int i = 0; i < M; i++) {
            cin >> W[i];
        }

        vector<vector<int>> weight(1 << M);
        for (int bit = 0; bit < 1 << M; bit++) {
            vector<int> S;
            for (int i = 0; i < M; i++) {
                if (!(bit & (1 << i))) {
                    S.push_back(W[i]);
                }
            }

            for (int s = 0; s < 1 << S.size(); s++) {
                int wei = 0;
                for (int i = 0; i < S.size(); i++) {
                    if (s & (1 << i)) {
                        wei += S[i];
                    }
                }
                weight[bit].push_back(wei);
            }
            weight[bit].erase(unique(weight[bit].begin(), weight[bit].end()), weight[bit].end());
            ranges::sort(weight[bit]);
        }

        map<int, int> cnt_mp;
        int ng_cnt = 0;
        for (int i = 0; i < N; i++) {
            bool ok = false; // 計測できるか
            vector<int> add; // 計測できない場合、どの重さを追加すればいいか

            for (int bit = 0; bit < (1 << M); bit++) {
                int right_w = 0;
                for (int j = 0; j < M; j++) {
                    if (bit & (1 << j)) {
                        right_w += W[j];
                    }
                }

                for (int weight_i : weight[bit]) {
                    if (right_w == (A[i] + weight_i)) {
                        // printf("ok:(%d,%d,%d)\n", right_w, A[i], weight_i);
                        ok = true;
                    } else if (right_w > (A[i] + weight_i)) {
                        // printf("%d - (%d + %d) = %d\n", right_w, A[i], weight_i, right_w - (A[i] + weight_i));
                        add.push_back(right_w - (A[i] + weight_i));
                    } else {
                        // printf("(%d + %d) - %d = %d\n", A[i], weight_i, right_w, (A[i] + weight_i) - right_w);
                        add.push_back((A[i] + weight_i) - right_w);
                    }
                }
            }

            // cout << "i=" << i << endl;
            // cout << "A[i]=" << A[i] << endl;
            if (!ok) {
                ng_cnt++;
                // cout << "ng" << endl;

                ranges::sort(add);
                add.erase(unique(add.begin(), add.end()), add.end());
                for (int vi : add) {
                    // cout << vi << " ";
                    cnt_mp[vi]++;
                }
                // cout << endl;
            }
            // cout << "--" << endl;
        }


        if (ng_cnt == 0) {
            cout << 0 << endl;
        } else {
            // cout << "ng_cnt: " << ng_cnt << endl;
            int ans = -1;
            for (auto [wei, cnt] : cnt_mp) {
                // cout << wei << " " << cnt << endl;
                if (cnt == ng_cnt) {
                    ans = wei;
                    break;
                }
            }
            cout << ans << endl;
        }
    }
}
accuracy: 1
time_ms: 5140
memory_kb: 113536
final_rank: 14

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

#include <atcoder/all>
using namespace atcoder;

using ll = long long;
using mint = modint998244353;

int main() {
  while(true) {
    int N, M;
    cin >> N >> M;
    if(N == 0 && M == 0) break;
    vector<ll> A(N), W(M);
    for(int i = 0; i < N; ++i) {
      cin >> A[i];
    }
    for(int i = 0; i < M; ++i) {
      cin >> W[i];
    }
    vector<bool> ok(N);
    unordered_set<ll> st;
    vector cand(N, unordered_set<ll>());
    for(int s = 0; s < 1 << M; ++s) {
      for(int t = (1 << M); t > 0; ) {
        t = (t - 1) & s;
        ll a = 0, b = 0;
        for(int i = 0; i < M; ++i) {
          if((t >> i) & 1) a += W[i];
          else if((s >> i) & 1) b += W[i];
        }
        st.insert(abs(a - b));
      }
    }
    for(int i = 0; i < N; i++) {
      for(ll d : st) {
        cand[i].insert(d + A[i]);
        cand[i].insert(abs(d - A[i]));
      }
    }
    vector<int> lack;
    for(int i = 0; i < N; ++i) {
      if(!cand[i].count(0)) {
        lack.push_back(i);
        // cout << i + 1 << endl;
        // cout << cand[i].count(1) << endl;
      }
    }
    if(lack.empty()) {
      cout << 0 << endl;
      continue;
    }
    ll INF = 1LL << 60;
    ll ans = 1LL << 60;
    for(ll x : cand[lack[0]]) {
      // cout << x << endl;
      bool ok = true;
      for(int i : lack) {
        if(!cand[i].count(x)) ok = false;
        if(!ok) break;
      }
      if(ok) ans = min(ans, x);
    }
    cout << (ans == INF ? -1 : ans) << endl;
  }
}
accuracy: 1
time_ms: 3350
memory_kb: 228000
final_rank: 16

code_snippet: #line 1 "C.cpp"
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
using ll = long long;
template<class T> inline bool chmax(T& a, const T& b) {if (a<b) {a=b; return true;} return false;}
template<class T> inline bool chmin(T& a, const T& b) {if (b<a) {a=b; return true;} return false;}
constexpr int INTINF = 1000001000;
constexpr int INTMAX = 2147483647;
constexpr ll LLMAX = 9223372036854775807;
constexpr ll LLINF = 4450000000011100000;

#line 1 "/home/harui/CompetitiveProgramming/library/debug.hpp"



#ifdef LOCAL
#define dbg(x) std::cerr << __LINE__ << " : " << #x << " = " << (x) << std::endl
#else
#define dbg(x) true
#endif

#line 12 "/home/harui/CompetitiveProgramming/library/debug.hpp"
#include <utility>
#include <set>


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

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

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& st) {
  os << '{';
  auto itr = st.begin();
  while (itr != st.end()) {
    os << *itr;
    itr = next(itr);
    if (itr != st.end()) os << ", ";
  }
  os << '}';
  return os;
}



#line 14 "C.cpp"

void solve(int N, int M) {
  // 1 <= N <= 100
  // 1 <= M <= 10

  vector<int>A(N);
  for (int i=0; i<N; i++) cin >> A[i];
  vector<int>W(M); for (int i=0; i<M; i++) cin >> W[i];


  set<ll>V; // 計れる重さの集合
  V.insert(0);
  for (int w : W) {
    set<ll> V2;
    for (ll v: V) {
      V2.insert(v+w);
      V2.insert(v-w);
    }
    for (ll v: V2) V.insert(v);
  }

  vector<ll> A2;
  for (int a: A) {
    if (!V.contains(a))A2.push_back(a);
  }

  if (A2.empty()) {
    cout << 0 << endl;
    return;
  }

  set<ll> Beta;
  {
    int a = A2[0];
    for (ll v: V) {
      Beta.insert(a-v);
      Beta.insert(v-a);
    }
  }


  for (int a : A2) {
    set<ll> Alphas;
    for (ll v: V) {
      Alphas.insert(a-v);
      Alphas.insert(v-a);
    }
    // Beta *= Alpha
    // \foarll b \in Beta, b \in Alpha
    vector<ll> Gamma; // { x | x \in Beta, x \notin 
    for (ll b: Beta) if (!Alphas.contains(b)) Gamma.push_back(b);
    for(ll g: Gamma) Beta.erase(g);
  }

  auto itr = Beta.lower_bound(0);
  if (itr != Beta.end()) {
    cout << *itr << endl;
  }
  else cout << -1 << endl;

}

int main() {
  ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  while (true) {
    int n, m; cin >> n >> m;
    if (n == 0 && m == 0) break;
    solve(n,m);
  }
  return 0;
}
accuracy: 1
time_ms: 7470
memory_kb: 19204
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
template<class T> bool chmin(T& a, T b) { return a > b ? a = b, true : false; }
template<class T> bool chmax(T& a, T b) { return a < b ? a = b, true : false; }
template<typename T>
concept Iterable = requires(T t) { std::begin(t); std::end(t); };
template<typename T>
	requires Iterable<T> && (!is_same_v<T, string>)
ostream& operator<<(ostream& os, const T& container) { for (auto& element : container) os << element << ' '; return os; }
template<typename R>
	requires ranges::range<R> && (!is_same_v<decay_t<R>, string>) && (!is_same_v<decay_t<R>, const char*>)
ostream& operator<<(ostream& os, R&& range) { for (auto& element : range)os << element << ' '; return os; }
template<typename T>
	requires Iterable<T> && (!is_same_v<T, string>)
istream& operator>>(std::istream& is, T& container) { for (auto& e : container)is >> e; return is; }
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
template<class T = ll> struct Edge {
	int to;
	T weight;
	bool operator==(Edge e) { return this->to == e.to and this->weight == e.weight; }
	bool operator<(Edge e) { return this->to == e.to ? this->weight < e.weight : this->to < e.to; }
};
#ifdef _DEBUG
#define SHOW(n) {const auto& _ret = n; cerr << #n << ": " << _ret << endl;}
#define MSG(x) cerr << x << endl;
#else
#define SHOW(n)
#define MSG(x)
#endif

//AtCoder Library 
//#include <atcoder/all>
//using namespace atcoder;
//using mint = modint998244353;
////using mint = modint1000000007;
////using mint1 = dynamic_modint<0>;
////using mint = modint;
////mint::set_mod();
//istream& operator>>(istream& is, mint& x) { ll r; is >> r; x = r; return is; }
//ostream& operator<<(ostream& os, mint& x) { os << x.val(); return os; }

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



int main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);

	while(true) {
		int n, m;
		cin >> n >> m;
		if (n == 0 and m == 0)return 0;

		vector<ll> a(n), w(m);
		cin >> a >> w;

		set<ll> b;
		auto dfs = [&](auto&& f, int i, ll v)->void {
			if (i == m) {
				if (v >= 0)b.insert(v);
				return;
			}

			f(f, i + 1, v);
			f(f, i + 1, v + w[i]);
			f(f, i + 1, v - w[i]);
			};

		dfs(dfs, 0, 0);

		vector<ll> memo;
		for (int i = 0; i < a.size(); ++i) {
			if (not b.contains(a[i])) {
				memo.push_back(i);
			}
		}

		if (memo.size() == 0) {
			cout << 0 << endl;
			continue;
		}

		ll v = a[memo[0]];

		//cout << "b:";
		//for (auto x : b) {
		//	cout << x << " ";
		//}
		//cout << endl;

		//SHOW(v);

		vector<ll> res;
		for (auto x : b) {
			ll d = abs(x - v);
			bool ok = true;
			for (int i = 0; i < a.size(); ++i) {
				if (!b.contains(a[i]) and !b.contains(abs(a[i] - d)) and !b.contains(a[i] + d)) {
					ok = false;
					break;
				}
			}

			if (ok)res.push_back(d);

			d = x + v;
			ok = true;
			for (int i = 0; i < a.size(); ++i) {
				//SHOW(a[i]);
				if (!b.contains(a[i]) and !b.contains(abs(a[i] - d)) and !b.contains(a[i] + d)) {
					ok = false;
					break;
				}
			}


			if (ok)res.push_back(d);
		}

		if (res.size() == 0)cout << -1 << endl;
		else cout << ranges::min(res) << endl;

	}




	return 0;
}
accuracy: 1
time_ms: 310
memory_kb: 5376
final_rank: 2