// ALDS1_12_A.cpp
// Graph II - Minimum Spanning Tree
#include <iostream>
using namespace std;

const int maxN = 100;
const int INF = 2001;
int w[maxN][maxN];
int color[maxN];
int n;
static const int WHITE = 0;
static const int BLACK = 1;

int prim(int x)
{
    int res = 0;
    int cnt = 1;
    color[x] = BLACK;
    while (cnt++ != n) {
        int minCost = INF;
        int pos = 0; // ??°?????°?????????
        for (int i = 0; i < n; i++) {
            if (color[i] != BLACK) continue;
            for (int j = 0; j < n; j++) {
                if (color[j] != WHITE) continue;
                if (w[i][j] < minCost) {
                    pos = j;
                    minCost = w[i][j];
                }
            }
        }
        res += minCost;
        color[pos] = BLACK;
    }
    return res;
}

int main()
{
    cin >> n;
    int num;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> num;
            if (num == -1) w[i][j] = INF;
            else w[i][j] = num;
        }
    }
    cout << prim(0) << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;

int main(){
  int n;
  cin >> n;
  vi p(n);
  int mn = 100000000, cnt = 0;
  rep(i,n){
    cin >> p[i];
    if(mn > p[i]){
      mn = p[i];
      cnt++;
    }
  }
  cout << cnt << endl;
}


#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define FOR(i, a, b) for(int i=(a);i<(b);i++)
#define REP(i, n) FOR(i, 0, n)
#define RFOR(i, a, b) for(int i=(a);i>=(b);i--)
#define RREP(i, n) RFOR(i, n, 0)
#define MFOR(i, m) for(auto i=(m).begin();i!=(m).end();i++)
#define ALL(a) (a).begin(), (a).end()
#define SZ(x) ((int)(x).size())

typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvll;

const double eps = 1e-10;
const int MOD = 1000000007;
const int INF = 1000000000;
const ll LINF = 1 << 30;

class UF {

  vector<int> par; // 親
  vector<int> rank; // 深さ

public:

  void init(int n) { // n個で初期化
    for(int i=0;i<n;i++) {
      par.push_back(i);
      rank.push_back(0);
    }
  }

  UF(int n) {
    for(int i=0;i<n;i++) {
      par.push_back(i);
      rank.push_back(0);
    }
  }

  int find(int x) { // 木の中のxの深さを返す
    if (par[x] == x) return x;
    else return par[x] = find(par[x]);
  }

  void unite(int x, int y) { // xとyを統合する
    x = find(x);
    y = find(y);
    if (x == y) return;

    if(rank[x] < rank[y]) {
      par[x] = y;
    } else {
      par[y] = x;
      if (rank[x] == rank[y]) rank[x]++;
    }
  }

  bool same(int x, int y) { // xとyが等しいかどうか判定する
    return find(x) == find(y);
  }
};

struct Edge {
  int from, to, cost;
};

bool operator<(const Edge& e1, const Edge& e2) {
  return e1.cost > e2.cost;
}

struct Point {
  int pos, x, y;
};

bool operator<(const Point& p1, const Point& p2) {
  return p1.x < p2.x;
}

bool operator>(const Point& p1, const Point& p2) {
  return p1.y < p2.y;
}

template<typename T>
void printv(vector<T> const& s) {
  REP(i, SZ(s)) {
    cout << s[i] << " ";
  }
  cout << endl;
}

int main () {
  cin.tie(0);
  cout << setprecision(10);

  int n; cin >> n;
  vector<Point> p(n);
  REP(i, n) {
    p[i].pos = i;
    cin >> p[i].x >> p[i].y;
  }

  vector<vector<Edge>> g(n);

  sort(ALL(p));
  REP(i, n-1) {
    Edge e;
    int cost = min(abs(p[i].x - p[i+1].x), abs(p[i].y - p[i+1].y));
    e.from = p[i].pos;
    e.to = p[i+1].pos;
    e.cost = cost;
    g[e.from].pb(e);
    swap(e.from, e.to);
    g[e.from].pb(e);
  }

  sort(ALL(p), greater<Point>());
  REP(i, n-1) {
    Edge e;
    int cost = min(abs(p[i].x - p[i+1].x), abs(p[i].y - p[i+1].y));
    e.from = p[i].pos;
    e.to = p[i+1].pos;
    e.cost = cost;
    g[e.from].pb(e);
    swap(e.from, e.to);
    g[e.from].pb(e);
  }

  UF uf(n);

  ll ans = 0;
  int cnt = 0;
  priority_queue<Edge> edges;
  REP(i, SZ(g[0])) {
    edges.push(g[0][i]);
  }

  while(cnt < n-1) {
    Edge next = edges.top(); edges.pop();
    if(!uf.same(next.from, next.to)) {
      uf.unite(next.from, next.to);
      ans += next.cost;
      cnt++;
      REP(i, SZ(g[next.to])) {
        edges.push(g[next.to][i]);
      }
    }
  }

  cout << ans << endl;

}

#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <functional>
#include <algorithm>
#include <climits>
#include <cmath>
#include <iomanip>
using namespace std;
#define ll long long int
#define rep(i,n) for( int i = 0; i < n; i++ )
#define rrep(i,n) for( int i = n; i >= 0; i-- )
#define REP(i,s,t) for( int i = s; i <= t; i++ )
#define RREP(i,s,t) for( int i = s; i >= t; i-- )
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define INF 2000000000
#define mod 1000000007
#define INF2 1000000000000000000

int v, e;
const int MAX_N = 100010;
// 隣接リスト
vector<int> g[MAX_N];
bool used[MAX_N];
// トポロジカルソートされた数列
vector<int> ans;
bool head[MAX_N];
void dfs(int u) {
  if(used[u]) return;
  used[u] = true;
  for(auto& i: g[u]) dfs(i);
  // 帰りがけ順で追加
  ans.push_back(u);
}

void tsort() {
  for(int i=0; i<v; ++i) dfs(i);
  reverse(ans.begin(), ans.end());
}

signed main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> v >> e;
    e += v - 1;
    rep(i, v) head[i] = true;
    for(int i=0; i<e; ++i) {
        int s, t;
        cin >> s >> t;
        s--; t--;
        g[s].push_back(t);
    }
    tsort();
    //for(int i: ans) cout << i + 1 << endl;
    vector<pair<int, int>> p;
    rep(i, v) p.push_back({i, ans[i]});
    rep(i, v) ans[i] = -1;
    sort(p.begin(), p.end());
    for(auto& e: p) {
        int u = e.second;
        //cerr << "*" << e.first << " " << e.second << endl;
        for(auto to: g[u]) {
            ans[to] = u;
        }
    }
    for(int i: ans) cout << i + 1 << endl;

    return 0;
}


#include <bits/stdc++.h>
#include <vector>
using namespace std;
long long n, d, hasil;
int main(){
	while(cin >> d){
		hasil = 0;
		for(int i = d; i <= 600-d; i += d){
			hasil += d * pow(i, 2);
		}
		cout << hasil << endl;
	}
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
#define rep(i,m,n) for(int i=m;i<n;i++)
ll mod=1e9+7;

int main(){
  int n;
  cin>>n;
  int a[n+2];
  a[0]=0;
  a[n+1]=0;
  rep(i,0,n) cin>>a[i+1];
  int sum[n+2];
  sum[0]=0;
  rep(i,0,n+1){
    sum[i+1]=sum[i]+abs(a[i+1]-a[i]);
  }

  int sum2[n+2];
  sum2[0]=0;
  rep(i,0,n+1){
    sum2[i+1]=sum2[i]+abs(a[n+1-i]-a[n-i]);
  }

  rep(i,1,n+1){
    cout<<sum[i-1]+sum2[n-i]+abs(a[i-1]-a[i+1])<<endl;
  }
}


#include <bits/stdc++.h>
using namespace std;
using int64 = long long;
#define int int64
#define rep(i, n) for(int i=0; i<n; i++)
#define FOR(i, a, b) for(int i=a; i<b; i++)
#define SORT(x) sort(x.begin(), x.end())
#define GSORT(x) sort(x.begin(), x.end(), greater<int>())
#define mk make_pair
#define fi first
#define se second
#define pb push_back
#define ALL(x) x.begin(), x.end()
#define V(T) vector<T>
typedef pair<int, int> P;
typedef pair<P, P> PP;
typedef vector<int> vi;
typedef vector<vi> vvi;
int max(int a, int b) {if(b>a) return b; else return a;}
int min(int a, int b) {if(b<a) return b; else return a;}

vvi con(100050);
V(bool) visited(100050, false);
vi bw(100050, 0);
bool exr = false;

void dfs(int now, int cost, int past) {
    bw[now] = cost%2;
    rep(i, con[now].size()) {
        if(!visited[con[now][i]]) {
            visited[con[now][i]] = true;
            dfs(con[now][i], cost+1, now);
        } else if(con[now][i] != past) {
            if(bw[con[now][i]]==bw[now]) exr = true;
        }
    }
}

signed main() {
    int N, M;
    cin >> N >> M;
    rep(i, M) {
        int a, b;
        cin >> a >> b;
        a--; b--;
        con[a].pb(b);
        con[b].pb(a);
    }

    dfs(0, 0, -1);

    if(exr) cout << N*(N-1)/2 - M << endl;
    else {
        int b=0, w=0;
        rep(i, N) {
            if(bw[i]==0) b++;
            else w++;
        }
        cout << b*w-M << endl;
    }

    return 0;
}

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

vector<vector<int>> graph;

void DFS(int v, int parent_v, vector<int> &depth, vector<int> &parent){
    for(int child_v : graph[v]){
        if(child_v == parent_v) continue;

        depth[child_v] = depth[v] + 1;
        parent[child_v] = v;
        DFS(child_v, v, depth, parent);
    }
}

int main(){
    int n, u, v;
    cin >> n >> u >> v;
    u -= 1;
    v -= 1;
    graph.resize(n);

    for(int i=0; i<n-1; i++){
        int a, b;
        cin >> a >> b;
        a -= 1;
        b -= 1;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }

    vector<int> depth(n), parent(n);
    DFS(v, -1, depth, parent);

    int init = depth[u];
    int start = u;
    for(int i=0; i<(init-1)/2; i++){
        start = parent[start];
    }
    int dist = depth[start] - (init-1)/2;

    vector<int> depth2(n), parent2(n);
    DFS(start, parent[start], depth2, parent2);

    sort(depth2.begin(),depth2.end());
    reverse(depth2.begin(),depth2.end());

    cout << (init-1)/2 + (depth2[0] + dist - 1) << endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define int long long
int hmt() {int x=0;int c=getchar(),n=0;for(;!isdigit(c);c=getchar()) n=(c=='-');for(;isdigit(c);c=getchar()) x=x*10+c-'0';if(n) x=-x;return x;}
#define in hmt()
#define ins ({string x;char c=getchar();for(;c==' '||c=='\n';c=getchar());for(;c!=' '&&c!='\n';c=getchar()) x+=c;x;})
#define forinc(i,a,b) for(int i=a,_b=b;i<=_b;++i)
#define fordec(i,a,b) for(int i=a;i>=b;--i)
#define forb(i,BS) for(int i=BS._Find_first();i< BS.size();i = BS._Find_next(i))
#define forv(a,b) for(auto &a:b)
#define pb push_back
#define pii pair<int,int>
#define fi first
#define se second
#define all(a) a.begin(),a.end()
#define reset(f,x) memset(f,x,sizeof(f))
#define bit(x,i) ((x>>(i-1))&1)
#define onbit(x,i) (x|(1<<(i-1)))
#define offbit(x,i) (x&~(1<<(i-1)))
const int N=200010;
int n,Q,A,B,a[N],oo,s[N],f[N],ans;
struct bit
{
	int t[N];
	void rs()
	{
	    reset(t,127);oo=t[0];
	}
	void upd(int i,int x)
	{
		for(;i<=n;i+=i&-i) t[i]=min(t[i],x);
	}
	int get(int i)
	{
		int g=oo;
		for(;i;i-=i&-i) g=min(g,t[i]);
		return g;
	}
}T[2];
void add(int i,int x)
{
	T[0].upd(i,x-i);
	T[1].upd(n-i+1,i+x);
}
main()
{
    //freopen("C.inp","r",stdin);
	n=in,Q=in,A=in,B=in;
	forinc(i,1,Q) a[i]=in;
	forinc(i,2,Q) s[i]=s[i-1]+abs(a[i]-a[i-1]);
	T[0].rs();T[1].rs();
	add(B,abs(A-a[1]));
	add(A,abs(B-a[1]));
	ans=s[Q]+min(abs(A-a[1]),abs(B-a[1]));
	forinc(i,2,Q)
	{
		f[i]=min(T[0].get(a[i])+a[i],T[1].get(n-a[i]+1)-a[i])+s[i-1];
		add(a[i-1],f[i]-s[i]);
		ans=min(ans,f[i]+s[Q]-s[i]);
	}
	cout<<ans<<"\n";
}

#include<bits/stdc++.h>
#define maxn 200005
#define LL long long
using namespace std;
const int mod = 1e9+7;
int n,Q,pre,now;
struct Seg{
	LL mn[maxn<<2],tag[maxn<<2]; int flg;
	Seg(){memset(mn,0x3f,sizeof mn);}
	inline void add(int i,LL v){mn[i]+=v,tag[i]+=v;}
	inline void down(int i){if(tag[i]) add(i<<1,tag[i]),add(i<<1|1,tag[i]),tag[i]=0;}
	void ins(int i,int l,int r,int x,LL v){
		if(l==r) {mn[i]=min(mn[i],v+l*flg);return;}
		int mid=(l+r)>>1; down(i);
		x<=mid?ins(i<<1,l,mid,x,v):ins(i<<1|1,mid+1,r,x,v);
		mn[i]=min(mn[i<<1],mn[i<<1|1]);
	}
	LL qry(int i,int l,int r,int x,int y){
		if(x<=l&&r<=y) return mn[i];
		int mid=(l+r)>>1; LL ret=mn[0]; down(i);
		if(x<=mid) ret=min(ret,qry(i<<1,l,mid,x,y));
		if(y>mid) ret=min(ret,qry(i<<1|1,mid+1,r,x,y));
		return ret;
	}
	LL whole(int i,int l,int r){
		if(l==r) return mn[i]+l;
		int mid=(l+r)>>1; down(i);
		return min(whole(i<<1,l,mid),whole(i<<1|1,mid+1,r));
	}
}T1,T2;
int main()
{
	scanf("%d%d%d%d",&n,&Q,&pre,&now),T1.flg=-1,T2.flg=1;
	T1.ins(1,1,n,now,0),T2.ins(1,1,n,now,0);
	for(int i=1;i<=Q;i++,pre=now){
		scanf("%d",&now); if(now==pre) continue;
		LL tmp=min(T1.qry(1,1,n,1,now)+now,T2.qry(1,1,n,now,n)-now);
		T1.add(1,abs(now-pre)),T2.add(1,abs(now-pre));
		T1.ins(1,1,n,pre,tmp),T2.ins(1,1,n,pre,tmp);
	}
	printf("%lld\n",T1.whole(1,1,n));
}


#include <cstdio>

using namespace std;

int main()
{
	int n;

	while (scanf("%d", &n), n != 0){
		int ice[10] = {0};
		int ice_n;
		for (int i = 0; i < n; i++){
			scanf("%d", &ice_n);
			ice[ice_n]++;
		}

		for (int i = 0; i < 10; i++){
			if (ice[i] == 0){
				puts("-");
			}
			else {
				while (ice[i]-- != 0){
					printf("*");
				}
				puts("");
			}
		}
	}
}

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	int l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2, sum, i;
	double ter;
	vector<int> s;
	while (scanf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", &l1, &l2, &l3, &l4, &l5, &l6, &l7, &l8, &l9, &l10, &v1, &v2) != EOF) {
		s.clear();
		s.push_back(l1);
		s.push_back(l2);
		s.push_back(l3);
		s.push_back(l4);
		s.push_back(l5);
		s.push_back(l6);
		s.push_back(l7);
		s.push_back(l8);
		s.push_back(l9);
		s.push_back(l10);
		sum = l1 + l2 + l3 + l4 + l5 + l6 + l7 + l8 + l9 + l10;
		ter = (double(sum*v1)) / (v1 + v2);
		sum = 0;
		for (i = 0; i < 10; i++) {
			sum += s[i];
			if (ter <= (double)sum) {
				cout << i + 1 << endl;
				break;
			}
		}
	}
	return 0;
}


#include <stdio.h>
#include <limits.h>
#include <algorithm>

using namespace std;

long long int sum = 0;

void merge(int A[],int left,int mid, int right){
    int a1 = mid - left;
    int a2 = right - mid;
    int l[a1+1],r[a2+1];
    for(int i = 0; i < a1; i++) l[i] = A[left + i];
    for(int i = 0; i < a2; i++) r[i] = A[mid + i];
    l[a1] = r[a2] =  INT_MAX;

    int i = 0, j = 0;
    for(int k = left;k < right; k++){
        if(l[i] < r[j]){
            A[k] = l[i++];
        }else{
            A[k] = r[j++];
            sum += a1 - i;
        }
    }
}

void mergeSort(int A[],int left,int right){
    if(left+1 < right){
        int mid = (left+right)/2;
        mergeSort(A,left,mid);
        mergeSort(A,mid,right);
        merge(A,left,mid,right);
    }
}

int main(){
    int n;
    scanf("%d",&n);
    int A[n];
    for(int i = 0; i < n; i++) scanf("%d",&A[i]);

    mergeSort(A,0,n);

    printf("%lld\n",sum);

}

#include <bits/stdc++.h>

typedef long long LL;
typedef unsigned long long ULL;
#define int long long
#define debug printf("fuck %d\n", __LINE__);

inline LL read() {
	LL res = 0, bo = 1;
	char ch = getchar();
	while (ch < '0' || ch > '9') {
		if (ch == '-') bo = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch <= '9') {
		res = (res << 1) + (res << 3) + ch - '0';
		ch = getchar();
	}
	return bo * res;
}

template <typename T>
void read(T &x) {
	x = read();
}

template <typename T, typename... Argv>
void read(T &a, Argv &... argv) {
	read(a);
	read(argv...);
}

const int N = 1e5 + 10;
int x[N], p[N], s, n;

LL Calc(int l, int r, int t) {
	if (s < x[l]) return x[r] - s;
	if (s > x[r]) return s - x[l];
	if (p[l] >= p[r]) return p[l] += p[r], Calc(l, r - 1, l) + (t == r ? x[r] - x[l] : 0);
	else return p[r] += p[l], Calc(l + 1, r, r) + (t == l ? x[r] - x[l] : 0);
}

signed main() {
	read(n, s);
	for (int i = 1; i <= n; ++ i) read(x[i], p[i]);
	std::cout << Calc(1, n, p[n] > p[1] ? 1 : n) << std::endl;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

template< typename T >
struct edge {
  int src, to;
  T cost;

  edge(int to, T cost) : src(-1), to(to), cost(cost) {}

  edge(int src, int to, T cost) : src(src), to(to), cost(cost) {}

  edge &operator=(const int &x) {
    to = x;
    return *this;
  }

  operator int() const { return to; }
};

template< typename T >
using Edges = vector< edge< T > >;
template< typename T >
using WeightedGraph = vector< Edges< T > >;
using UnWeightedGraph = vector< vector< int > >;
template< typename T >
using Matrix = vector< vector< T > >;

template< typename G >
struct LowLink {
  const G &g;
  vector< int > used, ord, low;
  vector< int > articulation;
  vector< pair< int, int > > bridge;

  LowLink(const G &g) : g(g), used(g.size()), ord(g.size()), low(g.size()) {}

  int build(int idx = 0, int k = 0, int par = -1) {
    used[idx] = true;
    ord[idx] = k++;
    low[idx] = ord[idx];
    bool is_articulation = false;
    int cnt = 0, ordmax = k;
    for(auto &to : g[idx]) {
      if(!used[to]) {
        ++cnt;
        ordmax = build(to, ordmax, idx);
        low[idx] = min(low[idx], low[to]);
        is_articulation |= ~par && low[to] >= ord[idx];
        if(ord[idx] < low[to]) bridge.emplace_back(idx, to);
      } else if(to != par) {
        low[idx] = min(low[idx], ord[to]);
      }
    }
    is_articulation |= par == -1 && cnt > 1;
    if(is_articulation) articulation.push_back(idx);
    return ordmax;
  }
};

int main() {
  int V, E;
  scanf("%d %d", &V, &E);
  UnWeightedGraph g(V);
  for(int i = 0; i < E; i++) {
    int x, y;
    scanf("%d %d", &x, &y);
    g[x].push_back(y);
    g[y].push_back(x);
  }
  LowLink< UnWeightedGraph > lowlink(g);
  lowlink.build();
  sort(lowlink.articulation.begin(), lowlink.articulation.end());
  for(auto &v : lowlink.articulation) printf("%d\n", v);
}

#include <iostream>
#include <vector>

using namespace std;

int dfs(auto& nodes, int current_index, int parent_index, int& time) {
    int children = 0;

    auto& current_node = nodes[current_index];
    current_node.time = time;
    current_node.low = time;

    for (auto adjacent_index : current_node.adjacent) {
        if (adjacent_index == parent_index) {
            continue;
        }

        auto& adjacent_node = nodes[adjacent_index];
        if (adjacent_node.time) {
            current_node.low = min(adjacent_node.time, current_node.low);
        } else {
            ++children;
            dfs(nodes, adjacent_index, current_index, ++time);

            if (current_node.time <= adjacent_node.low) {
                current_node.is_articulation_point = true;
            }

            current_node.low = min(adjacent_node.low, current_node.low);
        }
    }

    return children;
}

int main() {
    int n, m;

    cin >> n >> m;
    if (n == 0 || m == 0) {
        return 0;
    }

    struct node {
        int time{0};
        int low{0};
        bool is_articulation_point{false};
        vector<int> adjacent;
    };

    vector<node> nodes(n);
    for (int i = 0; i < m; ++i) {
        int from, to;
        cin >> from >> to;
        nodes[from].adjacent.push_back(to);
        nodes[to].adjacent.push_back(from);
    }

    int time = 0;
    nodes[0].is_articulation_point = dfs(nodes, 0, -1, ++time) > 1;

    for (int i = 0; i < nodes.size(); ++i) {
        if (nodes[i].is_articulation_point) {
            cout << i << endl;
        }
    }

    return 0;
}


#include <iostream>
using namespace std;

int F[102][102];

void setblock(int c, int d, int x, int y){
  if(d==0){
    for(int i=0;i<4;i++){
      F[y][x+i]=c;
      F[y+1][x+i]=c;
    }
  }else{
    for(int i=0;i<4;i++){
      F[y+i][x]=c;
      F[y+i][x+1]=c;
    }
  }

}

void DFS(int Y, int X, int c){
  if(F[Y][X]!=c)
    return;

  F[Y][X] = 6;

  DFS(Y-1, X  ,c);
  DFS(Y  , X+1,c);
  DFS(Y+1, X  ,c);
  DFS(Y  , X-1,c);
}

int main(){
  int w,h,xs,ys,xg,yg,n;
  while(true){
  cin >> w >> h;
  for(int i=0;i<h;i++){
   for(int k=0;k<w;k++){
     F[i][k]=-1;
   }
  }
  if(w==0&&h==0){
    break;
  }
  cin >> xs >> ys;
  cin >> xg >> yg;
  cin >> n;
  for(int i=0; i<n; i++){
    int c,d,x,y;
    cin >> c >> d >> x >> y;
    setblock(c,d,x,y);
  }

  DFS(ys,xs,F[ys][xs]);
  if(F[yg][xg]==6){
    cout << "OK" << endl;
  }else{
    cout << "NG" << endl;
  }
}
  return 0;
}

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<math.h>
#include<string>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
#include<utility>
#include<set>
#include<map>
#include<stdlib.h>
#include<iomanip>

using namespace std;

#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 1e9
#define MOD 1000000007
#define rep(i,n) for(i=0;i<n;i++)
#define loop(i,a,n) for(i=a;i<n;i++)
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)

typedef vector<int> vi;
typedef pair<int,int> pii;

int main(void) {
  int i,j;
  int n,q;
  while(1){
    cin>>n>>q;
    if(n==0 && q==0)break;
    vi v(105,0);
    rep(i,n){
      int m,a;
      cin>>m;
      rep(j,m){
	cin>>a;
	v[a]++;
      }
    }
    int ans=0;
    for(i=1;i<=100;i++)
      if(v[i]>v[ans] && v[i]>=q)ans=i;
    cout<<ans<<endl;
  }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int

void printVector(vector<int> v) {
    for (auto x : v) {
        cout << x << ' ';
    }
    cout << '\n';
}

void printArray(ll A[], int size) {
    for (int i = 0; i <= size - 1; i++) cout << A[i] << ' ';
}

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

    int n, q;
    cin >> n >> q;
    string s;
    cin >> s;
    vector<int> v;
    int tot = 0;
    for (int i = 0; i <= n - 1; i++) {
        if (i + 1 <= n - 1 && s[i] == 'A' && s[i + 1] == 'C') tot++;
        v.push_back(tot);
    }
    for (int i = n - 1; i >= 1; i--) {
        //cout << 'h' << '\n';
        v[i] = v[i - 1];
    }
    v[0] = 0;
    //printVector(v);
    while (q--) {
        int l, r;
        cin >> l >> r;
        l--;
        r--;
        cout << v[r] - v[l] << '\n';
    }
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll          long long
#define endl        "\n"
#define si(a)       scanf("%d",&a)
#define si2(a,b)    scanf("%d%d",&a,&b)
#define sl(a)       scanf("%lld",&a)
#define sl2(a,b)    scanf("%lld%lld",&a,&b)
#define pb          push_back
#define mk          make_pair
#define loop(n)     for(int i=0; i<n; i++)
#define FOR(a,b)    for(int i=a; i<=b; i++)
#define sz          size()
#define ff          first
#define ss          second
#define mem(a,val)  memset(a, val, sizeof(a))
#define md          1000000007
#define pi          acos(-1.0)

ll a[500010], bit[500010], n, m[500010], ans[500010];

pair< pair<ll,ll>, ll>p[500010];

void update(ll idx, ll val)
{
    while(idx<=n)
    {
        bit[idx]+=val;
        idx+= idx & (- idx);
    }
}

ll sum(ll idx)
{
    ll tot=0;
    while(idx>0)
    {
        tot+=bit[idx];
        idx-= idx & (- idx);
    }
    return tot;
}
int main()
{
    ll t,i,j,k,l,r,mn=0, mx=0;
    sl2(n,k);
    for( i=1; i<=n; i++)
    {
        sl(a[i]);
    }

    for(i=0; i<k; i++)
    {
        sl2(l,r);
        p[i].ff.ff=r;
        p[i].ff.ss=l;
        p[i].ss=i;
    }

    sort(p, p+k);
    /*for(i=0; i<k; i++)
    {
        cout<<p[i].ff.ss<<" "<<p[i].ff.ff<<" "<<p[i].ss<<endl;
    }*/
    memset(m, -1, sizeof(m));
    ll cnt=0;
    for( i=1; i<=n; i++)
    {
        if(m[a[i]]!=-1)
        {
            //cout<<i<<endl;
            update(m[a[i]], -1LL);
        }
        m[a[i]]=i;
        update(i, 1);

       // cout<<cnt<<" "<<p[i].ff.ff<<endl;
        while(cnt<k &&   p[cnt].ff.ff==i)
        {
            //cout<<p[i].ss<<" "<<sum(p[i].ff.ff)<<" "<<sum(p[i].ff.ss-1)<<endl;
            ans[p[cnt].ss] = sum(p[cnt].ff.ff) - sum(p[cnt].ff.ss-1);
            cnt++;
        }
    }

    for(i=0; i<k; i++)
    {
        printf("%lld\n", ans[i]);
    }

}


#include <vector>
#include <iostream>

using namespace std;

int main() {
    int n;
    cin >> n;
    int m = 1e9;
    for (int i = 0; i < n; i++) {
        int a;
        cin >> a;
        m = min(__builtin_ctz(a), m);
    }
    cout << m << endl;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int i=0;i<n;i++)
using ll = long long;
using pint = pair<int,int>;
using vpil = vector<pint>;
using vppil = vector<vpil>;

int main(){
    int n;
    cin >> n;
    vppil l(n);
    rep(i,n){
        int a;
        cin>>a;
        rep(j,a){
            pint xy;
            cin>>xy.first>>xy.second;
            xy.first--;
            l.at(i).push_back(xy);
        }
    }
    //end input
    //binary search
    int ans=0;
    rep(bit,1<<n){
        bool flag=true;
        rep(i,n){
            if(bit&(1<<i)){//is bit true
                //get items from l;
                for(pint xy:l.at(i)){
                    if((bit&(1<<xy.first))>>xy.first!=xy.second){
                        flag=false;
                        i+=n;
                        break;//=>gotonext
                    }
                }
            }
        }
        //gotonext
        if(flag){ans=max(__builtin_popcount(bit),ans);}
    }
    cout<<ans<<endl;
}


#include<bits/stdc++.h>
using namespace std;
#define rep(i,x,y) for(int i=x;i<y;i++)
#define print(A,x,n) rep(i,0,n){cout<<(i ? " ":"")<<A[i]x;}cout<<endl;
#define pprint(A,y,m,n) rep(j,0,m){print(A[j],y,n);}
const long mod=1e9+7;
const int size=1e5;
const int inf=1e9;
int main(){
	int H,W;cin>>H>>W;
	int A[H][W] = {}; int a;
	rep(i,0,H)rep(j,0,W){ cin>>a; A[i][j] += a; }
	rep(i,0,H)rep(j,0,W){ cin>>a; A[i][j] -= a; }
	bool dp[H+1][W+1][12801] = {}; dp[0][1][0] = 1;
	rep(i,1,H+1)rep(j,1,W+1){
        int t = abs(A[i-1][j-1]);
		rep(k,0,12801){
			if(k + t <= 12800) dp[i][j][k+t] |= dp[i-1][j][k] | dp[i][j-1][k];
            dp[i][j][abs(k - t)] |= dp[i-1][j][k] | dp[i][j-1][k];
		}
	}
	rep(i,0,12801){
		if(dp[H][W][i]){
            cout<<i<<endl;
            break;
        }
	}
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i=0; i<n; i++)
#define pb push_back
#define int long long
const int ofs = 12800;

int H, W;
int A[82][82], B[82][82];
bool dp[82][82][25610];

signed main() {
    cin.tie(0); ios::sync_with_stdio(false);
    cin >> H >> W;
    rep(i, H) rep(j, W) cin >> A[i][j];
    rep(i, H) rep(j, W) cin >> B[i][j];
    dp[0][0][A[0][0]-B[0][0]+ofs] = true;
    dp[0][0][B[0][0]-A[0][0]+ofs] = true;

    rep(i, H) rep(j, W) {
        if (i>0) rep(k, 25610) {
            if (!dp[i-1][j][k]) continue;
            int nk = k+A[i][j]-B[i][j];
            if (0<=nk && nk<25610) dp[i][j][nk] = true;
            nk = k+B[i][j]-A[i][j];
            if (0<=nk && nk<25610) dp[i][j][nk] = true;
        }
        if (j>0) rep(k, 25610) {
            if (!dp[i][j-1][k]) continue;
            int nk = k+A[i][j]-B[i][j];
            if (0<=nk && nk<25610) dp[i][j][nk] = true;
            nk = k+B[i][j]-A[i][j];
            if (0<=nk && nk<25610) dp[i][j][nk] = true;
        }
    }

    int ans = 1000000;
    rep(i, 25610) if (dp[H-1][W-1][i]) ans = min(ans, abs(i-ofs));
    cout << ans << endl;
}


#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <queue>
#include <stack>
#include <functional>
#include <bitset>
#include <assert.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(ll i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
const int inf = 1<<30;
const ll linf = 1LL<<62;
const int MAX = 510000;
ll dy[8] = {1,-1,0,0,1,-1,1,-1};
ll dx[8] = {0,0,1,-1,1,-1,-1,1};
const double pi = acos(-1);
const double eps = 1e-7;
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
	if(a>b){
		a = b; return true;
	}
	else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
	if(a<b){
		a = b; return true;
	}
	else return false;
}
template<typename T> inline void print(T &a){
    rep(i,a.size()) cout << a[i] << " ";
    cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){cout << a << " " << b << "\n";}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
	cout << a << " " << b << " " << c << "\n";
}
const int mod = 1e9 + 7;
//const int mod = 998244353;

void solve(){
    ll n; cin >> n;
    vl a(n); rep(i,n) cin >> a[i];
    vl basis;
    string s; cin >> s;
    ll ans = 0;
    for(ll i=n-1; i>=0; i--){
        for(auto b : basis){
            chmin(a[i], a[i]^b);
        }
        if(s[i]=='0'){
            if(a[i]) basis.push_back(a[i]);
        }else{
            if(a[i]) ans = 1;
        }
    }
    cout << ans << "\n";
}

int main(){
    ll t; cin >> t;
    while(t--){
        solve();
    }
}

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

typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> ii;
typedef tuple<ll, ll, ll> iii;
typedef vector<ll> vi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
#define REP(i,n) for (ll i = 0; i < n; ++i)
#define REPR(i,n) for (ll i = n-1; i >= 0; --i)
#define FOR(i,m,n) for (ll i = m; i < n; ++i)
#define FORR(i,m,n) for (ll i = n-1; i >= m; --i)
#define FORE(x,xs) for (const auto& x : xs)
#define FORI(i,v) for (auto i = v.begin(); i != v.end(); i++)
#define ALL(v) v.begin(), v.end()
#define CHMIN(x,y) x = min(x, y)
#define CHMAX(x,y) x = max(x, y)
#define YES(b) cout << ((b) ? "YES" : "NO") << endl
#define Yes(b) cout << ((b) ? "Yes" : "No") << endl

const int MAX = 2e5+10;
const int INF = 1e9+10;

int N;
vii U, D, R, L;

vii holRev(vii v) {
    vii ret;
    FORE (xy, v) {
        int x, y; tie(x, y) = xy;
        ret.push_back(ii(MAX-x, y));
    }
    return ret;
}

vii verRev(vii v) {
    vii ret;
    FORE (xy, v) {
        int x, y; tie(x, y) = xy;
        ret.push_back(ii(x, MAX-y));
    }
    return ret;
}

int sub1(vii r, vii l, bool hol) {
    int ret = INF;
    vector<set<int>> u(MAX);
    FORE (xy, l) {
        int x, y; tie(x, y) = xy; if (!hol) swap(x, y);
        u[y].insert(x);
    }
    FORE (xy, r) {
        int x, y; tie(x, y) = xy; if (!hol) swap(x, y);
        auto it = u[y].upper_bound(x);
        if (it != u[y].end()) {
            CHMIN(ret, (*it - x) * 5);
        }
    }

    return ret;
}

int sub2(vii uu, vii r) {
    int ret = INF;
    vector<set<int>> u(2*MAX+10);
    FORE (xy, uu) {
        int x, y; tie(x, y) = xy;
        u[x+y].insert(x);
    }
    FORE (xy, r) {
        int x, y; tie(x, y) = xy;
        auto it = u[x+y].upper_bound(x);
        if (it != u[x+y].end()) {
            CHMIN(ret, (*it - x) * 10);
        }
    }

    return ret;
}

int solve() {
    int ret = INF;

    // 正面衝突
    CHMIN(ret, sub1(R, L, true));
    CHMIN(ret, sub1(U, D, false));

    // 直行衝突
    CHMIN(ret, sub2(U, R));
    CHMIN(ret, sub2(holRev(U), holRev(L)));
    CHMIN(ret, sub2(verRev(D), verRev(R)));
    CHMIN(ret, sub2(holRev(verRev(D)), holRev(verRev(L))));

    return ret;
}

int main() {
    cout << fixed << setprecision(15);
    cin >> N;
    REP (i, N) {
        int x, y, c; char u; cin >> x >> y >> u;
        if (u == 'U') U.push_back(ii(x, y));
        else if (u == 'R') R.push_back(ii(x, y));
        else if (u == 'D') D.push_back(ii(x, y));
        else L.push_back(ii(x, y));

    }
    int ans = solve();
    if (ans == INF) cout << "SAFE" << endl;
    else cout << ans << endl;
}


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

int main(){

    int l,r;
    cin >> l >> r;
    const int num = 2019;
    int comp = INT_MAX;
    long long ans = 0;
    for(long long i=l; i<=r; i++){
        for(long long j=l; j<i; j++){
            ans = ((i%num) * (j%num))%num;
            if(ans < comp){
                comp = ans;
            }
            else if(ans == 0){
                cout << ans << endl;
                return 0;
            }
        }
    }
    cout << comp << endl;
}

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include <utility>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <cctype>
using namespace std;

#define MOD 2019

int main(){
  long long int L = 0,R = 0;
  cin >> L >> R;
  if(L + MOD <= R){
    cout << 0 << endl;
  }else{
  L = L % MOD;
  R = R % MOD;
  int answer = 100000000;
  for(int i = L;i < R;i++){
    for(int j = i + 1;j <= R;j++){
      answer = min(answer,((i*j)%2019));
    }
  }
  cout << answer << endl;
}
}


#include<stdio.h>
int main()
{
	char S[101];
	char T[101];
	scanf("%s %s", &S, &T);
	printf("%s%s",T,S);
	return 0;
}

#include <bits/stdc++.h>
#define ll long long
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define rrep(i, n) for (int i = 1; i <= n; i++)
ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; }
ll lcm(ll a, ll b) { return (a * b) / gcd(a,b); }
using P = pair <int, int>;
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; }

ll MOD = 1000000007;
ll INF =1<<30;

int main(){
    int n,h,w;
    cin >> n >> h >> w;
    cout << (n-h+1)*(n-w+1) <<endl;
}


#define _USE_MATH_DEFINES

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
//#include <atcoder/all>
using namespace std;
//using namespace atcoder;

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef tuple<ll, ll, ll> tl3;

//typedef modint998244353 mint;

const int BIG_NUM = 1e9;
const ll INF = 1000000000000000000;
const ll MOD = 1e9 + 7;
//const ll MOD = 998244353;

const ll MAX = 1e9 + 5;

int main() {
	int m;
	cin >> m;
	vector<int> d(m);
	vector<ll> c(m);

	for (int i = 0; i < m; i++) {
		cin >> d[i] >> c[i];
	}

	vector<vector<pll>> dl(10);

	for (int i = 0; i < 10; i++) {
		dl[i].emplace_back(make_pair(i, 0));
	}

	for (int i = 0; i < 10; i++) {
		for (int j = 0; j < 60; j++) {

			//cout << j << endl;
			ll num = dl[i][j].first * 2;
			ll cnt = dl[i][j].second * 2 + 1;

			if (num >= 10) {
				cnt++;
				num = num % 10 + 1;
			}
			dl[i].emplace_back(make_pair(num, cnt));
		}
		//cout << i << endl;
	}

	/*
	for (int i = 0; i < 10; i++) {
		for (int j = 0; j < 60; j++) {
			cout << dl[i][j].first << " ";// << dl[i][j].second << endl;
		}
		cout << endl;
	}
	*/

	ll cnt = 0;
	vector<int> a(m);
	for (int i = 0; i < m; i++) {
		int num = 0;
		cnt--;
		for (int b = 0; b < 60; b++) {

			if (((c[i] >> b) & 1) == 1) {
				num += dl[d[i]][b].first;
				cnt += dl[d[i]][b].second;
				cnt++;
				//cout << i << " " << dl[d[i]][b].second << " " << dl[d[i]][b].first << endl;
			}
			if (num >= 10) {
				num -= 9;
				cnt++;

			}
		}

		a[i] = num;

	}
	//cout << cnt << endl;
	int num = a[0];
	for (int i = 1; i < m; i++) {
		//cout << a[i] << endl;
		num += a[i];
		cnt++;
		if (num >= 10) {
			num -= 9;
			cnt++;

		}
	}

	cout << cnt << endl;
}

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
#define rrep(i, n) for (int i = n - 1; i >= 0; i--)
using namespace std;
#define INF ((1<<30)-1)
#define LINF (1LL<<60)
#define EPS (1e-10)
typedef long long ll;
typedef pair<ll, ll> P;
const int MOD = 1000000007;
const int MOD2 = 998244353;

ll c[200010], d[200010];
int main(){
    int m;
    cin >> m;
    rep(i, m) cin >> d[i] >> c[i];

    ll tot = 0, digit = 0;
    rep(i, m) {
        tot += d[i] * c[i];
        digit += c[i];
    }

    cout << digit - 1 + (tot - 1) / 9 << endl;

    return 0;
}


#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <memory>
#include <iomanip>

int main(int argc, char* argv[])
{
    while (true) {
        std::string line;
        std::stringstream buffer;
        getline(std::cin, line);
        buffer << line;
        size_t length = 0;
        buffer >> length;
        if (length == 0) break;
        int *total = new int[length + 1];
        size_t width = length + 1;
        memset(total, 0, sizeof(int) * width);
        for (size_t i = 0; i < length; ++i) {
            getline(std::cin, line);
            std::istringstream s(line);
            std::string element;
            int sum = 0;
            for (size_t n = 0; n < length; ++n) {
               getline(s, element, ' ');
               std::stringstream tmp;
                int val = 0;
                tmp << element;
                tmp >> val;
                sum += val;
                total[n] += val;
                std::cout << std::setw(5) << val;
            }
            std::cout << std::setw(5) << sum << std::endl;
            total[length] += sum;
        }
        for (size_t i = 0; i < width; ++i) {
            std::cout << std::setw(5) << total[i];
        }
        std::cout << std::endl;
        delete[] total;
    }
    return 0;
}


#include <bits/stdc++.h>

#define file(s) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)

#define Grt ch = getchar()
#define DeBug(x) std::cout << #x << '=' << x << std::endl

typedef long long ll;
const int MaxN = 45, MaxS = 1 << 18, mod = 1e9 + 7;

namespace IO
{
	char buf[1<<15], *fs, *ft;
	inline char getc() { return ft == fs && (ft = (fs = buf) + fread(buf, 1, 1<<15, stdin), ft == fs) ? 0 : *fs++; }
	template <typename T> inline void read(T &x)
	{
		x = 0;
		T f = 1, Grt;
		while (!isdigit(ch) && ch ^ '-') Grt;
		if (ch == '-') f = -1, Grt;
		while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), Grt;
		x *= f;
	}

	template <typename T, typename... Args>
	inline void read(T &x, Args &...args) { read(x); read(args...); }

	char Out[1<<24], *fe = Out;
	inline void flush() { fwrite(Out, 1, fe - Out, stdout); fe = Out; }
	template <typename T> inline void write(T x, char str)
	{
		if (!x) *fe++ = 48;
		if (x < 0) *fe++ = '-', x = -x;
		T num = 0, ch[20];
		while (x) ch[++ num] = x % 10 + 48, x /= 10;
		while (num) *fe++ = ch[num --];
		*fe++ = str;
	}
}

using IO::read;
using IO::write;

template <typename T> inline bool chkMin(T &a, const T &b) { return a > b ? (a = b, true) : false; }
template <typename T> inline bool chkMax(T &a, const T &b) { return a < b ? (a = b, true) : false; }
template <typename T> inline T min(T a, T b) { return a < b ? a : b; }
template <typename T> inline T max(T a, T b) { return a > b ? a : b; }

ll f[MaxN][MaxS], ans = 1;
int main()
{
	int n, x, y, z; read(n, x, y, z);
	int state = (1 << (x + y + z - 1)) |  (1 << (y + z - 1)) | (1 << (z - 1));
	int sum = (1 << (x + y + z)) - 1;
	f[0][0] = 1;
	for (int i = 1; i <= n; ++ i)
	{
		(ans *= 10) %= mod;
		for (int s = 0; s <= sum; ++ s) if (f[i - 1][s])
			for (int c = 1, now; c <= 10; ++ c)
			{
				now = (s << c) | (1 << (c - 1)), now &= sum;
				if ((now & state) != state) f[i][now] = (f[i][now] + f[i - 1][s]) % mod;
			}
	}
	for (int s = 0; s <= sum; ++ s) ans = (ans - f[n][s] + mod) % mod;
	write(ans, '\n');
	IO::flush();
	return 0;
}

#include <cstdio>
#include <vector>

using namespace std;

#define MAX_H 20
#define MAX_W 20

#define INF (1<<28)

int w, h;
int F[MAX_H][MAX_W];
int G[MAX_H][MAX_W];
int gy, gx;
int y, x;
int py, px;

void debug();

const int dy[] = {1, 0, -1, 0};
const int dx[] = {0, 1, 0, -1};
void move(int d) {
    //printf("    %d\n", d);
    while (F[y][x] == 0) {
        x += dx[d];
        y += dy[d];
    }
    if (F[y][x] == 3) return;
    F[y][x] = 0;
    y -= dy[d];
    x -= dx[d];
}

bool can_move(int d) {
    if (F[y+dy[d]][x+dx[d]] == 1) return false;
    int _y = y;
    int _x = x;
    while (F[_y][_x] == 0) {
        _y += dy[d];
        _x += dx[d];
        if (_y < 0 || h <= _y || _x < 0 || w <= _x) return false;
    }
    return true;
}

void debug() {
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            printf("%d ", F[i][j]);
        }
        printf("\n");
    }
}

int solve(int cur) {
    if (y == gy && x == gx) return 0;
    if (cur >= 10) return INF;
    int min_cost = INF;
    for (int i = 0; i < 4; i++) {
        if (can_move(i)) {
            int backup[h][w];
            int py = y, px = x;
            for (int j = 0; j < h; j++)
                for (int k = 0; k < w; k++)
                    backup[j][k] = F[j][k];
            move(i);
            min_cost = min(min_cost, solve(cur+1)+1);
            y = py, x = px;
            for (int j = 0; j < h; j++)
                for (int k = 0; k < w; k++)
                    F[j][k] = backup[j][k];
        }
    }
    return min_cost;
}

int main() {
    while (scanf("%d %d", &w, &h), w || h) {
        int sy, sx;
        for (int i = 0; i < h; i++)
            for (int j = 0; j < w; j++) {
                scanf("%d", &F[i][j]);
                if (F[i][j] == 2) {
                    y = i, x = j;
                    F[i][j] = 0;
                }
                if (F[i][j] == 3)
                    gy = i, gx = j;
            }
        int ans = solve(0);
        printf("%d\n", (ans > 10 ? -1 : ans));
    }
    return 0;
}


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

int main()
{
	int n;
	cin >> n;
	int compat[n][n];
	for (int q = 0; q < n; q++)
	{
		for (int w = 0; w < n; w++)
		{
			cin >> compat[q][w];
		}
	}
	ll dp[1<<n];
	for (int q = 0; q < (1<<n); q++)
	{
		dp[q] = 0;
		for (int w = 0; w < n; w++)
		{
			if ((q & (1<<w)) == 0)
			{
				continue;
			}
			for (int e = w+1; e < n; e++)
			{
				if ((q & (1<<e)) != 0)
				{
					dp[q] += compat[w][e];
				}
			}
		}
	}
	for (int q = 1; q < (1<<n); q++)
	{
		for (int w = q; w > 0; w = (w-1) & q)
		{
			dp[q] = max(dp[q], dp[w] + dp[w ^ q]);
		}
	}
	cout << dp[(1<<n)-1] << "\n";
	return 0;
}

#include <iostream>
#include <sstream>
#include <cstdio>
#include <stdlib.h>
#include <string>
#include <vector>
#include <algorithm>
#define N 8
using namespace std;
int row[N];
bool col[N],dpos[2*N-1],dneg[2*N-1];

void printBoard(){
  for(int i=0;i<N;i++){
    for(int j=0;j<N;j++){
      if(j==row[i])printf("Q");
      else printf(".");
    }
    printf("\n");
  }
}
void putqueen(int i){
  if(i == N){
    printBoard();
    return;
  }
  if (row[i]!=-1){
      putqueen(i+1);
  }
  else {
    for(int j=0;j<N;j++){
      if(col[j]||dpos[i+j]||dneg[i-j+N-1])continue;
      row[i]=j;
      col[j]=dpos[i+j]=dneg[i-j+N-1]= true;
      putqueen(i+1);
      row[i]=-1;
      col[j]=dpos[i+j]=dneg[i-j+N-1]= false;
    }
  }
}

int main(){
  int n,x,y;
  cin>>n;
  for(int i=0;i<N;i++)row[i]=-1;
  for(int i=0;i<n;i++){
    cin>>x>>y;
    row[x]=y;
    col[y]=dpos[x+y]=dneg[x-y+N-1]=true;
  }
  putqueen(0);

  return 0;
}


#include<bits/stdc++.h>

using namespace std;

#define ll  long long
#define ld  double

#define all(x)  x.begin(),x.end()
#define sz(x)   (int)x.size()

#define pb  emplace_back
#define X   first
#define Y   second

const int   N   = 2e5 + 5;

typedef pair<int,int>   ii;

vector<int> g[N];

int par[N];
int deg[N];

int main()  {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int n;  cin >> n;
    int m;  cin >> m;

    for(int i = 1 ; i < n + m ; ++i)    {
        int x;  cin >> x;
        int y;  cin >> y;

        g[x].pb(y);
        deg[y]++;
    }
    queue<int>  qu;
    vector<int> tp;

    for(int i = 1 ; i <= n ; ++i)
        if(!deg[i]) qu.push(i);

    while (qu.size())   {
        int u = qu.front(); qu.pop();

        tp.pb(u);

        for(int v : g[u])   {
            deg[v]--;
            if(!deg[v])
                qu.push(v);
        }
    }
    for(int x : tp)
    for(int v : g[x])
        par[v] = x;

    for(int i = 1 ; i <= n ; ++i)
        cout << par[i] << "\n";
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
const int MOD = 1000000007;

int main()
{
    int h, w;
    cin >> h >> w;
    int a[h][w];
    rep(i, h)
    {
        rep(j, w) cin >> a[i][j];
    }

    int cnt = 0;
    vector<tuple<int, int, int, int>> ans;
    //現在位置を示す値
    int i = 0, j = 0;
    while (1)
    {
        if (i % 2 == 0)
        {
            if (j == w - 1)
            {
                if (i == h - 1)
                    goto end;
                if (a[i][j] % 2 == 1)
                {
                    cnt++;
                    ans.emplace_back(i + 1, j + 1, i + 2, j + 1);
                    a[i + 1][j]++;
                }
                i++;
            }
            else
            {
                if (a[i][j] % 2 == 1)
                {
                    cnt++;
                    ans.emplace_back(i + 1, j + 1, i + 1, j + 2);
                    a[i][j + 1]++;
                }
                j++;
            }
        }
        if (i % 2 == 1)
        {
            if (j == 0)
            {
                if (i == h - 1)
                    goto end;
                if (a[i][j] % 2 == 1)
                {
                    cnt++;
                    ans.emplace_back(i + 1, j + 1, i + 2, j + 1);
                    a[i + 1][j]++;
                }
                i++;
            }
            else
            {
                if (a[i][j] % 2 == 1)
                {
                    cnt++;
                    ans.emplace_back(i + 1, j + 1, i + 1, j);
                    a[i][j - 1]++;
                }
                j--;
            }
        }
    }
end:
    cout << cnt << endl;
    rep(i, cnt)
    {
        cout << get<0>(ans[i]) << " " << get<1>(ans[i]) << " " << get<2>(ans[i]) << " " << get<3>(ans[i]) << endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
int main()
{
	string s,d[10];
	cin>>s;
	int i,j,a,b;
	a=s.size();
	int c[a-2];
	for(i=0;i<a-2;i++)
	{
		for(j=i;j<i+3;j++)
		{
			d[i]=d[i]+s[j];
		}
		c[i]=abs(753-stoi(d[i]));
	}
	sort(c,c+(a-2));
	cout<<c[0]<<endl;

}

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main(void)
{
	char s[10];
	int i,a,x=0,y=0,z=0,b=0,c=0,d=1000;
	scanf("%s",s);
	a=strlen(s);
	for(i=0;i<a-2;i++){
		x=s[i]-'0';
		y=s[i+1]-'0';
		z=s[i+2]-'0';
		b=(x*100)+(y*10)+z;
		c=753-b;
		if(c<0) c*=-1;
		if(d>c) d=c;
	}
	printf("%d\n",d);
	return 0;
}


// http://algorithms.blog55.fc2.com/blog-entry-66.html

#include <stdio.h>
#include <string.h>

#define M 100

int N,R[M+1],C[M][M],B[M][M];

void compute(){
	int i=0,j,k,cost;
	memset(C,99,sizeof(C));
	for(;i<N;i++)C[i][i]=0;
	for(j=1;j<N;j++)
		for(i=0;i<N - j; i++ )
			for (k = i; k < i + j; k++ ){
				cost = C[i][k] + C[k+1][i+j] + R[i]*R[k+1]*R[i+j+1];
				if(cost<C[i][i+j])C[i][i+j]=cost,B[i][i+j]=k;
			}
}

void order( int i, int j ){
	if(i==j)printf("M%d",i);
	else{
		printf("(");
		order( i, B[i][j]-1 ); order(B[i][j], j);
		printf(")");
	}
}

void input(){
	scanf("%d",&N);
	int z,i=0;
	for(;i<N;i++)scanf("%d%d",R+i,&z);
	R[i]=z;
}

void output(){
	printf("%d\n",C[0][N-1]);
	//order(0, N);
	//puts("");
}

main(){
	input();
	compute();
	output();
}

#include <stdio.h>

int main(){
 int n;
 scanf("%d",&n);
 while(n){
  int a=0,b=0,aa,bb;
  for(int i=n;i>0;i--){
   scanf("%d %d",&aa,&bb);
   if(aa>bb){
    a+=aa+bb;
   }else if(aa<bb){
    b+=aa+bb;
   }else{
    a+=aa;
    b+=bb;
   }
  }
  printf("%d %d\n",a,b);
  scanf("%d",&n);
 }
}


#include <bits/stdc++.h>
#define rep(a,n) for (ll a = 0; a < (n); ++a)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
typedef vector<vector<ll> > Graph;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
const ll INF = 1e18;

int main(){
    ll n;
    cin >> n;
    vector<ll>a(n);
    rep(i,n)cin>>a[i];
    set<ll>st;
    map<ll,ll>mp;
    rep(i,n){
        mp[a[i]]++;
        st.insert(a[i]);
    }
    ll ans = 0;
    for(ll i=40;i>=0;i--){
        ll now = pow(2,i);
        for(auto itr=mp.begin();itr!=mp.end();itr++){
            if(itr->second<=0)continue;
            ll f = itr->first;
            ll s = itr->second;
            if(f*2==now){
                while(s>1){//同一の数字のペア
                    ans++;
                    s-=2;
                    itr->second-=2;
                }
                continue;
            }
            ll x = now - f;
            if(!x>0)continue;
            if(st.find(x)==st.end())continue;
            if(mp[x]>0){
                ll c = min(s,mp[x]);
                ans += c;
                mp[x]-=c;
                itr->second-=c;
            }
        }
    }
    cout << ans << endl;
    return 0;
}

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxm=2e5+5;
const int mod=1e9+7;
int a[maxm];
int b[maxm];
int n;
signed main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    vector<int>ans;
    for(int i=n;i>=1;i--){
        int cnt=0;
        for(int j=i;j<=n;j+=i){
            cnt+=b[j];
        }
        if(cnt%2==a[i]){
            continue;
        }else{
            b[i]=1;
            ans.push_back(i);
        }
    }
    cout<<ans.size()<<endl;
    for(auto i:ans){
        cout<<i<<' ';
    }
    return 0;
}
/*

*/


#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for (int i = 0; i < n; i++)
typedef long long ll;
// Welcome to my source code!

struct Node {
    int key;
    Node *parent, *left, *right;
};

Node *root, *NIL;

void insertKey(int key) {
    Node *y = NIL;
    Node *x = root;
    Node *z;

    z = new Node;
    z->key = key;
    z->left = NIL;
    z->right = NIL;

    while (x != NIL) {
        y = x;
        if (z->key < x->key) {
            x = x->left;
        } else {
            x = x->right;
        }
    }
    z->parent = y;

    if (y == NIL) {
        root = z;
    } else {
        if (z->key < y->key) {
            y->left = z;
        } else {
            y->right = z;
        }
    }
}

Node* findKey(Node *u, int key) {
    while (u != NIL && u->key != key) {
        if (key < u->key) {
            u = u->left;
        } else {
            u = u->right;
        }
    }
    return u;
}

Node* getMinimum(Node *x) {
    while (x->left != NIL) x = x->left;
    return x;
}

Node* getSuccessor(Node *z) {
    if (z->right != NIL) return getMinimum(z->right);
    Node *y = z->parent;
    while (y != NIL && z == y->right) {
        z = y;
        y = y->parent;
    }
    return y;
}

Node* deleteNode(Node *z) {
    Node *y;
    Node *x;

    if (z->left == NIL || z->right == NIL) y = z;
    else y = getSuccessor(z);

    if (y->left != NIL) x = y->left;
    else x = y->right;

    if (x != NIL) x->parent = y->parent;

    if (y->parent == NIL) root = x;
    else if (y == y->parent->left) y->parent->left = x;
    else y->parent->right = x;

    if (y != z) z->key = y->key;
}

void inorder(Node *u) {
    if (u == NIL) return;
    inorder(u->left);
    printf(" %d", u->key);
    inorder(u->right);
}

void preorder(Node *u) {
    if (u == NIL) return;
    printf(" %d", u->key);
    preorder(u->left);
    preorder(u->right);
}

int main() {
    int m, k;
    string com;
    cin >> m;

    REP(i,m) {
        cin >> com;
        if (com == "print") {
            inorder(root);
            cout << '\n';
            preorder(root);
            cout << endl;
        } else {
            cin >> k;
            if (com == "insert") insertKey(k);
            else if (com == "find") {
                if (findKey(root, k) != NIL) cout << "yes" << endl;
                else cout << "no" << endl;
            } else {
                deleteNode(findKey(root, k));
            }
        }
    }
}

#include <stdio.h>
struct binary_tree{
    int n;
    int l;
    int r;
};
binary_tree bt[1000000];
int now=0,empty[1000000];
void push(int n,int t){
    if(now==0){
        bt[0].n=n;
        now++;
        return;
    }
    if(bt[t].n<n){
        if(bt[t].r==0){
            bt[t].r=empty[now];
            bt[bt[t].r].n=n;
            now++;
            return;
        }
        else push(n,bt[t].r);
    }
    if(bt[t].n>n){
        if(bt[t].l==0){
            bt[t].l=empty[now];
            bt[bt[t].l].n=n;
            now++;
            return;
        }
        else push(n,bt[t].l);
    }
}
void dfs(int n){
    printf(" %d",bt[n].n);
    if(bt[n].l!=0){
        dfs(bt[n].l);
    }
    if(bt[n].r!=0){
        dfs(bt[n].r);
    }
}
void print_sorted(int n){
    if(bt[n].l!=0){
        print_sorted(bt[n].l);
    }
    printf(" %d",bt[n].n);
    if(bt[n].r!=0){
        print_sorted(bt[n].r);
    }
}
bool find(int n,int t){
    if(bt[t].n==n)return true;
    if(bt[t].n<n){
        if(bt[t].r!=0)return find(n,bt[t].r);
        return false;
    }
    if(bt[t].l!=0)return find(n,bt[t].l);
    return false;
}
void delete_item(int n,int t,int p){
    if(bt[t].n==n){
        if(bt[t].r!=0&&bt[t].l!=0){
            int big=bt[t].r,bp=t;
            while(bt[big].l!=0){
                bp=big;
                big=bt[big].l;
            }
            bt[t].n=bt[big].n;
            if(bp!=t)bt[bp].l=bt[big].r;
            else bt[bp].r=bt[big].r;
            now--;
            empty[now]=big;
            bt[big].n=bt[big].l=bt[big].r=0;
            return;
        }
        if(bt[t].r==0){
            if(p==-1){
                now--;
                empty[now]=bt[t].l;
                bt[t]=bt[bt[t].l];
                bt[empty[now]].n=bt[empty[now]].l=bt[empty[now]].r=0;
                return;
            }
            if(bt[p].n>n)bt[p].l=bt[t].l;
            else bt[p].r=bt[t].l;
            now--;
            empty[now]=t;
            bt[empty[now]].n=bt[empty[now]].l=bt[empty[now]].r=0;
            return;
        }
        if(bt[t].l==0){
            if(p==-1){
                now--;
                empty[now]=bt[t].r;
                bt[t]=bt[bt[t].r];
                bt[empty[now]].n=bt[empty[now]].l=bt[empty[now]].r=0;
                return;
            }
            if(bt[p].n>n)bt[p].l=bt[t].r;
            else bt[p].r=bt[t].r;
            now--;
            empty[now]=t;
            bt[empty[now]].n=bt[empty[now]].l=bt[empty[now]].r=0;
            return;
        }
    }
    else if(bt[t].n>n){
        delete_item(n,bt[t].l,t);
        return;
    }
    else delete_item(n,bt[t].r,t);
}
int main(){
    int n,temp;
    char a[1000];
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        empty[i]=i;
        bt[i].n=bt[i].l=bt[i].r=0;
        scanf("%s",a);
        if(a[0]=='i'){
            scanf("%d",&temp);
            push(temp,0);
        }
        if(a[0]=='p'){
            print_sorted(0);
            printf("\n");
            dfs(0);
            printf("\n");
        }
        if(a[0]=='f'){
            scanf("%d",&temp);
            if(find(temp,0))printf("yes\n");
            else printf("no\n");
        }
        if(a[0]=='d'){
            scanf("%d",&temp);
            delete_item(temp,0,-1);
        }
    }
}


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

const int mod = 998244353;

int main() {
    int n, d0;
    cin >> n >> d0;

    if(d0 != 0) {
        cout << 0 << endl;
        return 0;
    }

    vector<int> d(100005);
    d.at(0) = 1;
    int max_d = 0;
    for(int i = 1; i < n; ++i) {
        int di;
        cin >> di;
        max_d = max(max_d, di);
        d.at(di)++;
    }

    if(d.at(0) != 1) {
        cout << 0 << endl;
        return 0;
    }

    ll ans = 1;
    int i = 1;
    while(i < n) {
        if(d.at(i) == 0) break;
        rep(j, d.at(i)) {
            ans *= d.at(i-1);
            ans %= mod;
        }
        ++i;
    }
    if(i < max_d) cout << 0 << endl;
    else cout << ans << endl;

    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 1LL<<62
#define inf 998244353

ll ch[100010];

// a^n mod を計算する
long long modpow(long long a, long long n, long long mod) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

int main() {
	ll n;
	cin>>n;
	for(ll i=0;i<n;i++){
		ll now;
		cin>>now;
		ch[now]++;
		if(i==0&&now!=0){
			cout << 0;
			return 0;
		}
	}
	if(ch[0]!=1){
		cout << 0;
		return 0;
	}
	ll cnt=ch[0];
	ll ans=1;
	for(ll i=1;;i++){
		if(ch[i]==0){
			cout << 0;
			return 0;
		}
		ans*=modpow(ch[i-1], ch[i], 998244353);
		ans%=inf;
		cnt+=ch[i];
		if(cnt==n){
			break;
		}
	}
	cout <<ans;
	// your code goes here
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
typedef  long long ll;
ll gcd(ll f , ll s){if(s==0)return f;else return gcd(s,f%s);}
int const N = 1000006;
ll const M = 998244353;
long double const ep = .000000000000000001;
int p[N];
queue<int>q;
ll Farray[1032][1032] , Sarray[1032][1023] , arr[1002][1003];
int main() {

	int n;cin >> n;
	if(n==2){
		cout << 4 << " " << 7 << endl << 23 << " " << 10 ;
		return 0;
	}
	for(int i = 2 ; i <= 1000 ; i++){
		if(!p[i]){
			for(int x = i + i; x <= 100000 ; x+=i)p[x] = 1;
		}
	}
	for(int i = 2 ; i <= 100000 ; i++)if(!p[i])q.push(i);
	pair<int,int>start = mp(0,0);
	for(pair<int,int> i = start ; i.first < n ; i.first += 2){
		int currP = q.front();
		q.pop();
		for(pair<int,int> x = i ; x.first < n && x.second < n ; x.first++ , x.second++){
			Farray[x.first][x.second] = currP;
		}
	}
	for(pair<int,int> i = mp(0,2) ; i.second < n ; i.second += 2){
		int currP = q.front();
		q.pop();
		for(pair<int,int> x = i ; x.first < n && x.second < n ; x.first++ , x.second++){
			Farray[x.first][x.second] = currP;
		}
	}

	for(pair<int,int> i = start ; i.second < n ; i.second += 2){
		int currP = q.front();
		q.pop();
		for(pair<int,int> x = i ; x.first < n && x.second >= 0 ; x.first++ , x.second--){
			Sarray[x.first][x.second] = currP;
		}
	}

	for(pair<int,int> i = mp(1+(n%2),n-1) ; i.first < n ; i.first += 2){
		int currP = q.front();
		q.pop();
		for(pair<int,int> x = i ; x.first < n && x.second >= 0 ; x.first++ , x.second--){
			Sarray[x.first][x.second] = currP;
		}
	}

	for(int i = 0 ; i < n ; i++)
		for(int x = 0 ; x < n ; x++)
			arr[i][x] = Farray[i][x] * Sarray[i][x];
	for(int i=0 ; i< n ; i++){
		for(int j=0 ; j< n ; j++){
			if((i + j)%2== 1){
				set<ll>s;
				if(i != 0){
					s.insert(Farray[i-1][j]);
					s.insert(Sarray[i-1][j]);
				}
				if(i != n-1){
					s.insert(Farray[i+1][j]);
					s.insert(Sarray[i+1][j]);
				}
				if(j != 0){
					s.insert(Farray[i][j-1]);
					s.insert(Sarray[i][j-1]);
				}
				if(j != n-1){
					s.insert(Farray[i][j+1]);
					s.insert(Sarray[i][j+1]);
				}
				arr[i][j] = 1;
				set<ll>::iterator it = s.begin();
				for(;it!=s.end() ; it++)arr[i][j]*= *(it);
				arr[i][j]++;
			}
		}
	}
	for(int i=0 ; i< n ; i++){
		for(int j=0 ; j< n ; j++){
			cout << arr[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}


#include<iostream>
#include<math.h>
#include<vector>
#include<array>
#include<algorithm>
#include<numeric>
#include<map>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vector<ll>> mat;
typedef pair<int,int> P;
ll mod=pow(10,9)+7;
ll INF=pow(10,18);

int main(){
    int N,M;scanf("%d %d",&N,&M);
    vec A(M);
    for(int i=0;i<M;i++) scanf("%lld",&A[i]);
    sort(A.begin(),A.end(),greater<ll>());
    vec n={0,2,5,5,4,5,6,3,7,6};
    mat dp(N+1,vec(M+1,0));
    //漸化式
    for(int i=0;i<N-1;i++){
        if(i>0 && dp[i][0]==0) continue;
        vec v;
        for(int j=0;j<M;j++){
            if(i+n[A[j]]>N) continue;
            v=dp[i];v[0]++;v[j+1]++;
            int t=dp[i+n[A[j]]][0];
            if(v[0]>t){
                dp[i+n[A[j]]]=v;
            }
            else if(v[0]==t){
                for(int k=1;k<=M;k++){
                    if(v[k]>dp[i+n[A[j]]][k]){
                        dp[i+n[A[j]]]=v;
                        break;
                    }
                    else if(v[k]<dp[i+n[A[j]]][k]){
                        break;
                    }
                }
            }
        }
    }
    string ans;
    for(int i=0;i<M;i++){
        char c=A[i]+'0';
        for(int j=0;j<dp[N][i+1];j++) ans+=c;
    }
    cout<<ans<<endl;
    return 0;
}

#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (int)(n); i++)
#define REP(i,n) for (int i = 1; i < (int)(n); i++)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define debug(var) do{cout << #var << " : "; view(var);}while(0)
template<class T> bool chmin(T &a, T b) {if(a>b) {a=b;return 1;}return 0;}
template<class T> bool chmax(T &a, T b) {if(a<b) {a=b;return 1;}return 0;}
using namespace std;
template<class T> void view(T e) {cout << e << endl;}
template<class T> void view(const vector<T> &v) {for(const auto &e : v){cout << e << " ";} cout << endl;}
template<class T> void view(const vector<vector<T>> &vv) {for(const auto &v : vv){view(v);}}
using vint = vector<int>;
using vvint = vector<vector<int>>;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<int,int>;
const int inf = 1e9;
const ll inf_l = 1e18;
const int MAX = 1e5;

int main() {
    int n, m; cin >> n >> m;
    vint change = {0,2,5,5,4,5,6,3,7,6};
    vint a(m);
    rep(i,m) cin >> a[i];
    set<int> st;
    rep(i,m) st.insert(change[a[i]]);
    vint dp(n+1,-1);
    dp[0] = 0;
    REP(i,n+1) {
        for (auto x : st) {
            if (i-x >= 0 && dp[i-x] != -1) {
                chmax(dp[i],dp[i-x]+1);
            }
        }
    }
    int n_split = dp[n];
    sort(rall(a));
    string ans;
    while (n_split--) {
        rep(i,m) {
            if (n-change[a[i]] < 0) continue;
            if (dp[n-change[a[i]]] == dp[n] - 1) {
                ans += to_string(a[i]);
                n -= change[a[i]];
                break;
            }
        }
    }
    cout << ans << endl;
}


#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

int main(){
    int a,b;
    cin>>a>>b;
    int ans=0;
    for(int i=a;i<=b;i++){
        int s[5];
        int x=i;
        for(int j=0;j<5;j++){
            s[j]=x%10;
            x/=10;
        }
        if(s[0]==s[4]&&s[1]==s[3])ans++;
    }
    cout<<ans<<endl;
    return 0;
}

#include <stdio.h>

int main (){

    int G, N;
    scanf("%d %d", &G, &N);
    int z = 1;

for (int i = 0; i < G; i++) {
        if (2 * z <= z + N) {
            z *= 2;
        } else {
            z += N;
        }
    }
    printf("%d", z);

    return 0;
}


#include<bits/stdc++.h>
using namespace std ;
#define ll long long
#define pb push_back
#define mod 998244353
const ll N =30005 ;
ll dp[2*N] ;

int main ()
{
    ll n , t ;
    cin>> n >> t ;
    ll i ,j,x,y;
    dp[0] = 1 ;
    vector<pair<ll,ll> > v(n) ;
    for(i = 0 ; i< n ;i++) cin >> v[i].first >> v[i].second ;
    sort(v.begin(),v.end()) ;
    for(i = 1 ; i<= n ; i++) {
        x = v[i-1].first , y = v[i-1].second ;
        for (j = t-1 ; j>=0 ; j--) if (dp[j]) dp[j+x] = max(dp[j+x],dp[j]+y) ;

    }
    ll ans = 0 ;
    for (i = 0 ; i<2*N ; i++) ans = max(ans,dp[i]) ;
    cout << ans -1 << endl ;
    return 0 ;
}

#include<bits/stdc++.h>
#define reg register

const int maxn = 1000005;

int N;

char S[maxn];
char T[maxn];

int main(){
        scanf("%d", &N);
        scanf("%s%s", S+1, T+1);
        int flag = 1;
        for(reg int i = 1; i <= N; i ++)
                if(S[i] != T[i]){ flag = 0; break ; }
        if(flag){ printf("0\n"); return 0; }
        int Min_l = N, Ans = 1;
        std::queue <int> Q;
        for(reg int i = N; i >= 1; i --){
                Min_l = std::min(i, Min_l);
                if(T[i] == T[i-1]) continue ;
                while(Min_l && S[Min_l] != T[i]) Min_l --;
                if(!Min_l){ printf("-1\n"); return 0; }
                while(!Q.empty()){
                        if(Q.front()-Q.size()+1 > i) Q.pop();
                        else break ;
                }
                Q.push(Min_l);
                if(Min_l != i) Ans = std::max(Ans, (int)Q.size() + 1);
        }
        printf("%d\n", Ans);
        return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int N=200005;
long long a[N],l[N],r[N];
int main()
{
	ios::sync_with_stdio(false);
	int n;
	long long d,ret=0;
	cin>>n>>d;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		ret+=a[i];
	}
	ret+=(n-1)*d;
	r[1]=a[1];
	for(int i=2;i<=n;i++)
		r[i]=min(a[i],r[i-1]+d);
	l[n]=a[n];
	for(int i=n-1;i>=1;i--)
		l[i]=min(a[i],l[i+1]+d);
	for(int i=2;i<n;i++)
		ret+=min(l[i],r[i]);
	cout<<ret<<endl;
	return 0;
}

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

typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> vi;

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fi first
#define se second
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int i=m;i<(n);i++)
#define ALL(c) (c).begin(),(c).end()
#define dump(x) cout << #x << " = " << (x) << endl

class unionfind {
	vector<int> par, rank;

public:
	void init(int n) {
		par.resize(n);
		rank.resize(n);

		for (int i = 0; i < n; i++) {
			par[i] = i;
			rank[i] = 0;
		}
	}

	int find(int x) {
		if (par[x] == x) return x;
		else return par[x] = find(par[x]);
	}

	void unite(int x, int y) {
		x = find(x);
		y = find(y);
		if (x == y) return ;

		if (rank[x] < rank[y]) par[x] = y;
		else {
			par[y] = x;
			if (rank[x] == rank[y]) ++rank[x];
		}
	}

	bool same(int x, int y) { return (find(x) == find(y)); }
} uf;

const int MN = 200010;

using P = pair<ll, int>;

vector<pii> g[MN];
int col[MN];
ll X[MN];
vector<P> dp[MN];

void mergevec(vector<P>& a, vector<P> b) {
	for (auto p : b) {
		a.eb(p);
	}
	sort(ALL(a));

	set<int> st;
	vector<P> res;

	for (P p : a) {
		if (res.size() == 2) {
			break;
		}
		if (!st.count(p.se)) {
			st.insert(p.se);
			res.eb(p);
		}
	}
	a = res;
}

void dfs_up(int v, int p) {
	dp[v].eb(X[v], col[v]);

	for (pii e : g[v]) {
		if (e.fi != p) {
			dfs_up(e.fi, v);

			vector<P> nx;

			for (auto t : dp[e.fi]) {
				nx.eb(t.fi + e.se, t.se);
			}

			mergevec(dp[v], nx);
		}
	}
}

void dfs_down(int v, int p, int pw) {
	if (p != -1) {
		vector<P> nx;
		for (auto t : dp[p]) {
			nx.eb(t.fi + pw, t.se);
		}
		mergevec(dp[v], nx);
	}

	for (pii e : g[v]) {
		if (e.fi != p) {
			dfs_down(e.fi, v, e.se);
		}
	}
}

int N, D;

int main() {
	cin >> N >> D;
	rep(i, N) cin >> X[i];

	rep(i, N-1) {
		int a = i;
		int b = i + 1;
		int c = D;
		g[a].eb(b, c);
		g[b].eb(a, c);
	}

	uf.init(N);
	rep(i, N) {
		col[i] = i;
	}

	ll ans = 0;

	while (true) {
		bool one = true;
		for (int i = 1; i < N; ++i) {
			if (col[i] != col[0]) {
				one = false;
			}
		}
		if (one) {
			break;
		}

		rep(i, N) {
			dp[i].clear();
		}

		vector<P> mt(N, mp(LLONG_MAX, -1));

		dfs_up(0, -1);
		dfs_down(0, -1, -1);

		rep(i, N) {
			for (P p : dp[i]) {
				if (p.se != col[i]) {
					mt[col[i]] = min(mt[col[i]], mp(p.fi + X[i], p.se));
					break;
				}
			}
		}

		rep(i, N) if (mt[i] != mp(LLONG_MAX, -1)) {
			int u = i, v = mt[i].se;
			ll cost = mt[i].fi;
			if (!uf.same(u, v)) {
				uf.unite(u, v);
				ans += cost;
			}
		}

		rep(i, N) {
			col[i] = uf.find(col[i]);
		}
	}

	cout << ans << endl;

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(void){
  int n,u,v; cin>>n>>u>>v;
  vector<vector<int>> t(n+1,vector<int>(0));
  for(int i=0; i<n; ++i){
    int a,b; cin>>a>>b;
    t[a].push_back(b),t[b].push_back(a);
  }
  vector<int> ud(n+1,0),vd(n+1,0);
  vector<bool> d(n+1,true);
  queue<pair<int,int>> q;
  q.push({v,0}); d[v]=false;
  while(!q.empty()){
    int x=q.front().first,y=q.front().second; q.pop();
    vd[x]=y;
    for(auto& i:t[x]) if(d[i]==true) q.push({i,y+1}),d[i]=false;
  }
  int res=0;
  d=vector<bool>(n+1,true);
  q.push({u,0}); d[u]=false;
  while(!q.empty()){
    int x=q.front().first,y=q.front().second; q.pop();
    ud[x]=y; if(vd[x]>ud[x]) res=max(vd[x]-1,res);
    for(auto& i:t[x]) if(d[i]==true) q.push({i,y+1}),d[i]=false;
  }
  cout<<res;
  return 0;
}

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

vector<int>adj[100003],leaf;
int par[100003],depth[100005],sparse[100005][20],root=0,lz=0;

int lca(int p,int q)
{

    int a,b,c,d,lp,i,j;

    if(depth[p]<depth[q])
    {
        c=p; p=q; q=c;
    }

    for(j=19;j>=0;j--)
    {
         if((depth[p]-(1 << j))>=depth[q])
         {
             p=sparse[p][j];  if(depth[p]==depth[q])break;
         }
    }

    if(p==q){ return p; }
    else
    {
         for(j=19;j>=0;j--)
         {
             if(sparse[p][j]!=0 && sparse[p][j]!=sparse[q][j])
             {

                 p=sparse[p][j]; q=sparse[q][j];

                 if(par[p]==par[q])break;
             }

         }

         return par[p];
    }

}

void dfs(int src)
{
    int sz=adj[src].size();

    if(sz==1 && src!=root){   leaf.push_back(src);  lz++;   }

    for(int lp=0;lp<sz;lp++)
    {
        int u=adj[src][lp];

        if(u!=root && par[u]==0)
        {
            par[u]=src; sparse[u][0]=src; depth[u]=depth[src]+1;
            dfs(u);

        }

    }

}

int main()
{

    int n,m,a,b,i,j,u,v,ans,z,x,y,fr,sc,tr,w;
    scanf("%d %d %d",&n,&u,&v);

    for(i=1;i<=n-1;i++)
    {
        scanf("%d %d",&a,&b);
        adj[a].push_back(b); if(root==0){  if(adj[a].size()==2)root=a;  }
        adj[b].push_back(a); if(root==0){  if(adj[b].size()==2)root=b;  }

    }

    if(n==2)printf("0\n");
    else
    {
       dfs(root);

       for(j=1;j<=19;j++)
       {
           for(i=1;i<=n;i++)
           {
               if(sparse[i][j-1]!=0)
               {
                   sparse[i][j]=sparse[sparse[i][j-1]][j-1];
               }
           }
       }

       m=lca(u,v);

       ans=(depth[v]-depth[m])+(depth[u]-depth[m]); ans=ans-1;

       for(i=0;i<lz;i++)
       {
           y=leaf[i]; m=lca(u,y); w=lca(v,y);

           fr=(depth[u]-depth[m])+(depth[y]-depth[m]);
           sc=(depth[v]-depth[w])+(depth[y]-depth[w]);

           if(fr<sc)
           {
               if(sc-1>ans)ans=sc-1;
           }

       }

       printf("%d\n",ans);

    }

    return 0;
}


#include <iostream>
using namespace std;

string s;

int main() {
    cin >> s;
    if (s.length() % 2 != 0) {
        cout << "No\n";
        return 0;
    }
    bool works = true;
    for (int i=0; i<s.length(); i+=2) {
        if (s[i] != 'h' || s[i + 1] != 'i')
            works = false;
    }
    if (works)
        cout << "Yes\n";
    else
        cout << "No\n";
}

#include <bits/stdc++.h>
#define ll				long long int
#define fast			ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define vi 			vector<int>
#define vll 			vector<long long int>
#define all(v)			v.begin(),v.end()
const ll MOD = 1e9 + 7;
const ll INF = 10000000000000000;
const ll MAX_N = 1e5 + 7;
using namespace std;
//vector<bool> h(10000001,1);

int main(){
	string s;
	cin >> s;
	int n = (int)s.size();
	n/=2;
	string b="";
	for(int i =0;i<n;i++)
	b+="hi";
	//cout << b << '\n';
	if(b==s)cout << "Yes";
	else cout << "No";
}


#include <iostream>
#include <limits.h>

using namespace std;

int dp[100][100];
int p[101];
int n;

void solve() {
	for (int m = n; m > 0; m--) {
		for (int t = 0, i = 0, j = n - m + 1; t < n && j < n; t++) {
			dp[i][j] = INT_MAX;
			for (int k = i; k < j; k++) {
				int temp = dp[i][k] + dp[k + 1][j] + p[i] * p[k + 1] * p[j + 1];
				if (temp < dp[i][j]) {
					dp[i][j] = temp;
				}
			}
			i++;
			j++;
		}
	}
}

int main() {
	int a, b;
	cin >> n >> a;

	p[0] = a;
	for (int i = 1; i < n; i++) {
		cin >> a >> b;
		p[i] = a;
	}
	cin >> a;
	p[n] = a;

	solve();
	cout << dp[0][n - 1] << endl;

	return 0;
}


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

#define pb(n) push_back(n)
#define fi first
#define se second
#define all(r) (r).begin(),(r).end()
#define gsort(st,en) sort((st),(en),greater<int>())
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)
#define vvl(v,w,h,init) vector<vector<ll>> v(w,vector<ll>(h,init));

#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))

using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using dict = map<string,int>;
using pii = pair<int,int> ;
using pll = pair<ll,ll> ;

const int mod = 1000000007;
constexpr int imax = ((1<<30)-1)*2+1 ;
constexpr int inf = 100000000;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0,1,-1,1,-1};
const int dx[] = {0,-1,0,1,1,-1,-1,1};

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

struct data{
  ll i,j,k;
  vector<ll> v;
  ll ooo(set<ll> ok){
    ll cnt = 0,part,flag = 0;
    v.resize(3);
    v[0] = i;
    v[1] = j;
    v[2] = k;
    for(auto n:ok){
      rep(i,3){
        if(v[i] == n){
          flag |= (1 << i);
          ++cnt;
        }
      }
    }
    if(cnt == 2){
      rep(i,3){
        if(!(flag & (1 << i))){
          return v[i];
        }
      }
    }
    return -1;
  }
};

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  ll a,b,c;
  while(cin >> a >> b >> c && a && b && c){
    ll n;
    set<ll> ok;
    set<ll> wrong;
    vector<data> qes;
    cin >> n;
    ll x,y,z,w;
    rep(i,n){
      cin >> x >> y >> z >> w;
      --x,--y,--z;
      if(w == 1){
        ok.insert(x);
        ok.insert(z);
        ok.insert(y);
      }
      else{
        qes.push_back({x,y,z});
      }
    }
    rep(i,qes.size()){
      wrong.insert(qes[i].ooo(ok));
    }
    rep(i,a+b+c){
      if(find(all(ok),i) != ok.end()){
        cout << 1<<endl;
      }
      else if(find(all(wrong),i) != wrong.end()){
        cout << 0 <<endl;
      }
      else
        cout << 2 << endl;
    }
  }
  return 0;
}

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

#define loop(i,n) for(int i=1;i<=n;i++)
struct test {
	int i, j, k;
};

vector<test> t;
int p[302];

int main(){
	int a, b, c, n, i, j, k, r;
	while (cin >> a >> b >> c){
		cin >> n;
		t.clear();
		loop(i, a + b + c)p[i] = 2;
		loop(h, n){
			cin >> i >> j >> k >> r;
			if (r == 1){
				p[i] = p[j] = p[k] = 1;
			}
			else{
				t.push_back({ i, j, k });
			}
		}
		for (int h = 0; h < t.size(); h++){
			i = t[h].i; j= t[h].j; k = t[h].k;
			if (p[i] == 1 && p[j] == 1){
				p[k] = 0;
			}
			else if (p[j] == 1 && p[k] == 1){
				p[i] = 0;
			}
			else if (p[k] == 1 && p[i] == 1){
				p[j] = 0;
			}
		}
		loop(i, a + b + c)cout << p[i] << endl;
	}
	return 0;
}


#include <iostream>
using namespace std;

const int INF = 1 << 30;
const int dx[] = { 0, 0, 1, -1 };
const int dy[] = { 1, -1, 0, 0 };

int W, H;
int B[32][32];

int dfs(int x, int y, int times) {
  if(times == 10) return INF;

  int best = INF;

  for(int i = 0; i < 4; i++) {
    int j = 1;

    for(; ; j++) {
      int ny = y + dy[i] * j, nx = x + dx[i] * j;

      if(nx < 0 || W <= nx || ny < 0 || H <= ny) {
        break;
      }

      if(B[ny][nx] == 1) {
        if(j == 1) {
          break;
        }

        B[ny][nx] = 0;
        best = min(best, dfs(nx - dx[i], ny - dy[i], times + 1));
        B[ny][nx] = 1;
        break;
      }

      if(B[ny][nx] == 3) {
        return times + 1;
      }
    }
  }

  return best;
}

int main() {
  for(; cin >> W >> H && W; ) {
    int sx = -1, sy = -1;

    for(int y = 0; y < H; y++) {
      for(int x = 0; x < W; x++) {
        cin >> B[y][x];

        if(B[y][x] == 2) {
          sx = x;
          sy = y;
        }
      }
    }

    int res = dfs(sx, sy, 0);
    cout << (res == INF ? -1 : res) << endl;
  }
}

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 1e5 + 10;
int N;
int a[1001][1001], vis[MAXN], prime[MAXN], tot;
void GetPhi() {
	vis[1] = 1;
	for(int i = 2; i; i++) {
		if(!vis[i]) prime[++tot] = i;
		if(tot == 1000) break;
		for(int j = 1; j <= tot && (i * prime[j] <= 10000); j++) {
			vis[i * prime[j]] = 1;
			if(!(i % prime[j])) break;
		}
	}
}
int lcm(int x, int y) {
	if(x == 0 || y == 0) return x + y;
	return x / __gcd(x, y) * y;
}
main() {
	GetPhi();
	cin >> N;
	if(N == 2) {
		printf("4 7\n23 10");
		return 0;
	}
	for(int i = 1; i <= N; i++)
		for(int j = 1; j <= N; j++)
			if(!((i + j) & 1)) a[i][j] = prime[(i + j) / 2] * prime[N + (i - j) / 2 + (N + 1) / 2];
	for(int i = 1; i <= N; i++)
		for(int j = 1; j <= N; j++)
			if(!a[i][j])
				a[i][j] = lcm(lcm(a[i - 1][j], a[i][j - 1]), lcm(a[i][j + 1], a[i + 1][j])) + 1;
	for(int i = 1; i <= N; i++, puts(""))
		for(int j = 1; j <= N; j++)
			cout << a[i][j] << " ";
	return 0;
}


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

int main() {
    int a, b, c;
    cin >> a >> b >>c;

    if (a < b) {
        if (a <= c && c <= b)
            puts("Yes");
        else
            puts("No");
    }
    else {
        if (b <= c && c <= a)
            puts("Yes");
        else
            puts("No");
    }
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(k,i,n) for(ll i=k;i<n;++i)
int main(void){
    ll a,b,c;
    cin>>a>>b>>c;
    if(a>b)swap(a,b);
    rep(a,i,b+1){
        if(i==c){
            cout<<"Yes";
            return 0;
        }
    }
    cout<<"No";
}


#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#include <bits/stdc++.h>
using namespace std;
template<class t> inline t read(t &x){
	char c=getchar();bool f=0;x=0;
	while(!isdigit(c)) f|=c=='-',c=getchar();
	while(isdigit(c)) x=(x<<1)+(x<<3)+(c^48),c=getchar();
	if(f) x=-x;return x;
}
template<class t> inline void write(t x){
	if(x<0) putchar('-'),write(-x);
	else{if(x>9) write(x/10);putchar('0'+x%10);}
}

#define int long long

const int N=205;
int basis[65],n,a[N],b[N];

void insert(int x){
	for(int i=59;~i;i--) if(x>>i&1){
		if(basis[i]) x^=basis[i];
		else{
			basis[i]=x;
			return ;
		}
	}
}

bool exists(int x){
	for(int i=59;~i;i--) if(x>>i&1){
		if(basis[i]) x^=basis[i];
		else return 0;
	}
	return 1;
}

bool doit(){
	read(n);
	for(int i=0;i<60;i++) basis[i]=0;
	for(int i=1;i<=n;i++) read(a[i]);
	for(int i=1;i<=n;i++) scanf("%1d",&b[i]);
	for(int i=n;i;i--){
		if(!b[i]) insert(a[i]);
		else if(!exists(a[i])) return 1;
	}
	return 0;
}

signed main(){
	int t;
	read(t);
	while(t--) write(doit()),puts("");
}

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main(void){
    int T, N;
    long long Abuf;
    vector<long long> A;
    string S;
    cin >> T;
    for(int itestcase=0; itestcase<T; itestcase++){
        cin >> N;
        A.clear();
        for(int i=0; i<N; i++){
            cin >> Abuf;
            A.push_back(Abuf);
        }
        cin >> S;
        vector<long long> DP;
        DP.push_back(0);
        for(int i=N-1; i>=0; i--){
            Abuf = A[i];
            for(long long v: DP)Abuf = min(Abuf, Abuf^v);
            if(S[i]=='0'){
                DP.push_back(Abuf);
            }else if(Abuf != 0LL){
                DP.clear();
                break;
            }
        }
        if(DP.empty()){
            cout << 1 << endl;
        }else{
            cout << 0 << endl;
            DP.clear();
        }
    }
    return 0;
}


#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(), (x).end()
#define ll long long
#define INF 1000000000000000000
typedef pair<ll, ll> pll;

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

    int N, K;
    cin >> N >> K;
    vector<ll> x;
    rep(i, N) {
        ll a;
        cin >> a;
        if (a == 0) {
            K--;
            N--;
        } else
            x.push_back(a);
    }

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

    int a = lower_bound(all(x), 0) - x.begin();
    ll ans = INF;
    int s = a - K, t = a - 1;
    int cnt = 0;
    while (cnt <= K) {
        if (s < 0 || t >= N) {
            cnt++;
            s++;
            t++;
            continue;
        } else if (x[s] * x[t] < 0) {
            ans = min(ans, abs(x[s] * 2) + abs(x[t]));
            ans = min(ans, abs(x[s]) + abs(x[t] * 2));
        } else
            ans = min(ans, max(abs(x[s]), abs(x[t])));
        cnt++;
        s++;
        t++;
    }

    cout << ans << endl;
    return 0;
}

#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <string.h>
#include <ctype.h>
#include <algorithm>

using namespace std;

int main() {
  int n,ans,W[310000] = {},E[310000] = {};
  string s;
  cin >> n >> s;

  for(int i = 1; i <= n-1; i++) {
    if(s[i-1] == 'W')
      W[i] = W[i-1] + 1;
    else W[i] = W[i-1];
  }
  for(int i = n-2; i >= 0; i--) {
    if(s[i+1] == 'E')
      E[i] = E[i+1] + 1;
    else E[i] = E[i+1];
  }

  int m = n;
  for(int i = 0; i < n; i++)
    m = min(m,W[i]+E[i]);

  cout << m << endl;
}


#include <iostream>
using namespace std;

#define loop(i,a,b) for(int i=(a); i<(int)(b); i++)
#define rep(i,b) loop(i,0,b)

int main() {
    int n,m;
    cin>>n>>m;
    int A[1000], B[1000];
    rep(i,n) cin>>A[i];
    int c[1000]={};
    rep(i,m) cin>>B[i];
    rep(j,m)rep(i,n){
        if(B[j]>=A[i]){
            c[i]++;
            break;
        }
    }
    int mx=0, num=0;
    rep(i,n){
        if(mx<c[i]){
            num=i; mx=c[i];
        }
    }
    cout<<num+1<<endl;
}

#include <bits/stdc++.h>
using namespace std;
#define BE(x) x.begin(), x.end()

int main() {
    long long l, r;
    cin >> l >> r;

    long long ans = 2019;
    int icnt = 0;
    for (long long i = l; i < r; i++) {
        int jcnt = 0;
        for (long long j = i+1; j <= r; j++) {
            ans = min(ans, i*j%2019);
            jcnt++;
            if (jcnt == 2020) break;
        }
        icnt++;
        if (icnt == 2020) break;
    }
    cout << ans << endl;
}


  /*  HARD WORK FOREVER PAYS  */
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define turbo(){	\
	ios_base::sync_with_stdio(false); \
	cin.tie(NULL); \
}
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
typedef unsigned long long int ull;

vector<ull> allPrimes;

void sieve(int n)
{

    vector<bool> prime(n+1, true);

    for (int p=2; p*p<=n; p++)
    {

        if (prime[p] == true)
        {

            for (int i=p*2; i<=n; i += p)
                prime[i] = false;
        }
    }

    for (int p=2; p<=n; p++)
        if (prime[p])
            allPrimes.push_back(p);
}

ull factorialDivisors(ull n)
{
    sieve(n);

    ull result = 1;

    for (int i=0; i < allPrimes.size(); i++)
    {

        ull p = allPrimes[i];
        ull exp = 0;
        while (p <= n)
        {
            exp = exp + (n/p);
            p = p*allPrimes[i];
        }

        result = result*(exp+1)%1000000007;
    }

    return result;
}

int main()
{
	int n;
	cin>>n;
    cout << factorialDivisors(n)<<endl;
    return 0;
}

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

int main(){
	long long n;
	long long ans = 1;
	cin >> n;

	vector<int>  fact(10000); //factor container

    for(int j = 2; j<=n;j++){

    long long num = j;

	for (int i = 2; i <= num; i++) {
		    while (num%i == 0) { // 素数で割り切れなくなるまで割っていく
			     fact.at(i)++; //割った個数を配列に足す
			    num /= i;
		    }
	}

    }

    for(int i = 0; i < 1003; i++){
            ans *= (fact.at(i) + 1);
            ans %= 1000000007;
    }

    cout << ans << endl;

}


#include <stdio.h>
#include <queue>
using namespace std;

int main()
{
	const int INF = 10000000;
	int n, k, map[100][100], a, b, c;
	priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q;

	while(true)
	{
		scanf("%d%d", &n, &k);
		if(n == 0 && k == 0)
			break;

		for(int i = 0; i < n; ++i)
		{
			for(int j = 0; j < n; ++j)
				map[i][j] = INF;
		}

		for(int g = 0; g < k; ++g)
		{
			scanf("%d", &a);
			if(a == 0)
			{
				//vZ
				int ans = -1;
				bool flag[100] = {};

				scanf("%d%d", &a, &b);
				q.push(pair<int, int>(0, a - 1));

				while(!q.empty())
				{
					pair<int, int> p = q.top();
					q.pop();
					int &cost = p.first, &num = p.second;
					if(flag[num])
						continue;
					flag[num] = true;

					if(num == b - 1)
					{
						ans = cost;
						for(int i = q.size(); i > 0; --i)
							q.pop();
						break;
					}

					for(int i = 0; i < n; ++i)
					{
						if(map[num][i] == INF || flag[i])
							continue;
						q.push(pair<int, int>(cost + map[num][i], i));
					}
				}

				printf("%d\n", ans);
			}
			else
			{
				//ÇÁ
				scanf("%d%d%d", &a, &b, &c);
				if(map[a - 1][b - 1] > c)
					map[a - 1][b - 1] = map[b - 1][a - 1] = c;
			}
		}
	}

	return 0;
}

#include <iostream>
#include <algorithm>
using namespace std;
#define INF 100000000

int map[100][100];
int n,k,cou,tmin;
int dd[101],col[100];

int main(){
  int t,a,b,c,d,e;
  cin >> n >> k;
  while(n!=0&&k!=0){
    for (int i=0;i<10000;i++)map[i/100][i%100]=0;
    for (int i=0;i<k;i++){
      cin >> t;
      //      for (int y=0;y<k;y++){
      //for (int x=0;x<k;x++)
      //  cout << map[y][x] << " ";
      //cout << endl;
      //}
      if (t == 0){
	cin >> a >> b;
	for (int j=0;j<101;j++)dd[j]=INF;
	for (int j=0;j<101;j++)col[j]=0;
	dd[a-1]=0;
	cou = 1;
	col[a-1]=1;
	for (int m=0;m<n;m++)
	  if(map[a-1][m]>0)
	    dd[m]=min(dd[m],dd[a-1]+map[a-1][m]);

	while (cou < n){
	  tmin=100;
	  for (int m=0;m<n;m++)
	    if (col[m]==0)
	      if (dd[tmin]>dd[m]) tmin = m;

	  // for (int m=0;m<n;m++)cout << dd[m] << " ";//Dbg
	  // cout << endl;//Dbg

	  col[tmin]=1;
	  cou ++;

	  for (int m=0;m<n;m++)
	    if(map[tmin][m]>0)
	      dd[m]=min(dd[m],dd[tmin]+map[tmin][m]);
	}
	if (dd[b-1]==INF)cout << -1 << endl;
	else cout << dd[b-1] <<endl;
      }else{
	cin >> c >> d >> e;
	c--;d--;
	if (map[c][d]==0){
	  map[c][d]=e;
	  map[d][c]=e;
	}
	map[c][d]=min(map[c][d],e);
	map[d][c]=min(map[d][c],e);
      }
    }
    cin >> n >> k;
  }
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

template <typename A, typename B>
string to_string(pair<A, B> p);

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);

string to_string(const string& s) {
  return '"' + s + '"';
}

string to_string(const char* s) {
  return to_string((string) s);
}

string to_string(bool b) {
  return (b ? "true" : "false");
}

string to_string(vector<bool> v) {
  bool first = true;
  string res = "{";
  for (int i = 0; i < static_cast<int>(v.size()); i++) {
    if (!first) {
      res += ", ";
    }
    first = false;
    res += to_string(v[i]);
  }
  res += "}";
  return res;
}

template <size_t N>
string to_string(bitset<N> v) {
  string res = "";
  for (size_t i = 0; i < N; i++) {
    res += static_cast<char>('0' + v[i]);
  }
  return res;
}

template <typename A>
string to_string(A v) {
  bool first = true;
  string res = "{";
  for (const auto &x : v) {
    if (!first) {
      res += ", ";
    }
    first = false;
    res += to_string(x);
  }
  res += "}";
  return res;
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
  return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
  return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}

void debug_out() { cerr << endl; }

template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
  cerr << " " << to_string(H);
  debug_out(T...);
}

#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

int main() {
  ios:: sync_with_stdio(false);
  cin.tie();
  long long n;
  cin >> n;
  long long mi;
  cin >> mi;
  for (int i = 0; i < 4; i++) {
    long long x;
    cin >> x;
    mi = min(mi, x);
  }
  long long ans = 5 - 1 + (n + (mi - 1)) / mi;
  cout << ans;
  return 0;
}

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

void solve(ll N, ll A, ll B, ll C, ll D, ll E) {
  ll bn = min({A, B, C, D, E}); // bottle neck
  cout << ((N - 1) / bn + 5) << endl;
}

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

  ll N, A, B, C, D, E;
  cin >> N >> A >> B >> C >> D >> E;

  solve(N, A, B, C, D, E);

  return 0;
}


#include<bits/stdc++.h>
using namespace std;
using lli = long long;
#define rep(i,n) for(int i=0;i<n;i++)
#define N 100100

lli n;

int main(void){
	cin >> n;
	vector<lli> v(n);
	vector<lli> e(N), o(N);
	rep(i, n) cin >> v[i];
	rep(i, n){
		if(i%2 == 0){
			e[v[i]]++;
		}else{
			o[v[i]]++;
		}
	}
	auto p1 = max_element(e.begin(), e.end())-e.begin();
	auto p2 = max_element(o.begin(), o.end())-o.begin();
	if(p1 != p2){
		cout << n-e[p1]-o[p2] << endl;
	}else{
		if(e[p1] < o[p2]){
			e[p1] = 0;
			lli ne = *max_element(e.begin(), e.end());
			cout << n-ne-o[p2] << endl;
		}else if(e[p1] == o[p2]){
			lli tmp = e[p1];
			e[p1] = o[p2] = 0;
			lli noe = max(*max_element(e.begin(), e.end()),
			*max_element(o.begin(), o.end()));
			cout << n-tmp-noe << endl;
		}else{
			o[p2] = 0;
			lli no = *max_element(o.begin(), o.end());
			cout << n-e[p1]-no << endl;
		}
	}

	return 0;
}

#include <bits/stdc++.h>
using namespace std;
//vector<vector<int>> a(5, vector<int>(5, 0)) 5*5-0
int main(){
    long long int n;
    cin >> n;
    vector<int> a(n);
    for(int i = 0; i < n; i++){
        cin >> a.at(i);
    }
    long long int step = 0;
    for(int i = 1; i < n; i++){
        if(a.at(i - 1) > a.at(i)){
            step += a.at(i - 1) - a.at(i);
            a.at(i) = a.at(i - 1);
        }
    }

    cout << step << endl;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef struct{
	int n, cost;
}Data;

typedef struct{
	Data data;
	int prior;
}node;

typedef struct{
	node* nodes;
	int arr_sz;  //???????????????????????????
	int que_sz;  //?¬????????´?????????´????????????
}priority_queue;

node* my_realloc(node* old_ptr, int old_sz, int new_sz){
	node* new_ptr = (node*)malloc(sizeof(node) * new_sz);
	if(old_sz){
		memcpy(new_ptr, old_ptr, sizeof(node) * old_sz);
		free(old_ptr);
	}
	return new_ptr;
}

void push(priority_queue *q, Data d, int prior){
	if(q->que_sz >= q->arr_sz){
		int new_sz = (q->arr_sz ? q->arr_sz * 2 : 8);
		q->nodes = my_realloc(q->nodes, q->arr_sz, new_sz);
		q->arr_sz = new_sz;
	}

	int k = q->que_sz;

	while(true){
		if(k == 0)break;

		int next = (k - 1) / 2;
		if(q->nodes[next].prior > prior){
			q->nodes[k] = q->nodes[next];
			k = next;
		}
		else break;
	}

	q->nodes[k].data = d;
	q->nodes[k].prior = prior;

	++q->que_sz;
}

Data pop(priority_queue *q){
	Data ret = q->nodes[0].data;

	q->nodes[0] = q->nodes[--q->que_sz];

	int k = 0;
	while(true){
		int l = k * 2 + 1, r = k * 2 + 2;
		int next = -1;

		if(l < q->que_sz)next = l;
		if(r < q->que_sz)next = (q->nodes[r].prior < q->nodes[l].prior ? r : l);

		if(next == -1)break;

		if(q->nodes[next].prior < q->nodes[k].prior){
			q->nodes[k] = q->nodes[next];
			k = next;
		}
		else break;
	}

	q->nodes[k] = q->nodes[q->que_sz];

	return ret;
}

typedef struct{
	int to, cost;
}Edge;

#define maxN  100005
#define maxM  500001
#define inf 2000000000

int cost[maxN];
Edge *g[maxN];
int g_sz[maxN], cnt[maxN];
int n, m, r;
int s[maxM], t[maxM], d[maxM];

void dijkstra(int k){
	priority_queue que = {0};
	for (int i = 0; i < n; ++i)cost[i] = inf;
	cost[k] = 0;
	Data d;
	d.n = k, d.cost = 0;
	push(&que, d, d.cost);

	while (que.que_sz){
		d = pop(&que);

		int v = d.n;
		if (cost[v] < d.cost)continue;
		for (int i = 0; i < g_sz[v]; ++i){
			Edge e = g[v][i];
			if (cost[e.to] > cost[v] + e.cost){
				cost[e.to] = cost[v] + e.cost;

				Data x;
				x.n = e.to, x.cost = cost[e.to];
				push(&que, x, x.cost);
			}
		}
	}
}

int main(void){
	scanf("%d%d%d", &n, &m, &r);

	for(int i = 0; i < m; ++i){
		scanf("%d%d%d", &s[i], &t[i], &d[i]);

		++cnt[s[i]];
	}

	for(int i = 0; i < n; ++i){
		g[i] = (Edge*)malloc(sizeof(Edge) * cnt[i]);
	}

	for(int i = 0; i < m; ++i){
		Edge e;
		e.to = t[i], e.cost = d[i];
		g[s[i]][g_sz[s[i]]++] = e;
	}

	dijkstra(r);

	for(int i = 0; i < n; ++i){
		if(cost[i] == inf)printf("INF\n");
		else printf("%d\n", cost[i]);
	}

	return 0;
}


#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
	int x,y,z;
	int ans=0;
	x=y=z=0;
	char c='\0';
	string s;
	cin>>s;
	for(int i=0;i<s.size();i++){
		bool f=true;
		if(s[i]=='J'){
			if(c=='J')x++;
			else {
				x=1;
				y=z=0;
			}
		}else if(s[i]=='O'){
			if(c=='J' || c=='O')y++;
			else f=false;
		}else{
			if(c=='O' || c=='I'){
				z++;
				if(y<=x && y<=z)ans=max(ans,y);
			}
			else f=false;
		}
		if(f)c=s[i];
		else c='\0';
	}
	cout<<ans<<endl;
	return 0;
}

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

int main() {

  int N, M = 0, h = 0;
  cin >> N;
  M = N;

  for(int i = 0; i < 10; i++) {
    h += M % 10;
    M = M / 10;
    if(M == 0) {
      break;
    }
  }

  if(N % h == 0) {
  	cout << "Yes" << endl;
  }

  else {
    cout << "No" << endl;
  }

}


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

#define _GLIBCXX_DEBUG

//vector<int> A(M), B(M);
//vector<vector<char>> answer(N, vector<char>(N, '-'));

int main() {
  string s;
  int ans = 0;

  cin >> s;

  if(s[0] == 'R'){
    ans++;
    if(s[1] == 'R'){
      ans++;
      if(s[2] == 'R') ans++;
    }
  }

  else{
    if(s[1] == 'R'){
      ans++;
      if(s[2] == 'R') ans++;
    }
    else{
      if(s[2] == 'R') ans++;
    }
  }

  cout << ans << endl;

  return 0;
}

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<iomanip>
#define pi 3.14159265358979323846
#define ll long long
#define rep(i, a, n) for(int i = a; i < n; i++)
using namespace std;
int main(){
  string s;
  cin >> s;
  if(s == "RRR"){
    cout << "3\n";
    return 0;
  }
  if(s == "RRS" || s == "SRR"){
    cout << "2\n";
    return 0;
  }
  if(s == "SSS"){
    cout << "0\n";
    return 0;
  }
  cout << "1\n";
  return 0;
}


#include <iostream>
using namespace std;
typedef long long int LLI;
int main()
{
  	LLI n, t, tmp, next, ans;
  	cin >> n >> t >> tmp;
  	ans = t;
  	for(int i = 1; i < n; i++)
    {
      cin >> next;
      if( next - tmp >= t )
        ans += t;
      else
        ans += next - tmp;
      tmp = next;
    }
  	cout << ans;
	return 0;
}

#include<bits/stdc++.h>
using namespace std;
///Welcome to Nasif's Code
#define bug printf("bug\n");
#define bug2(var) cout<<#var<<" "<<var<<endl;
#define co(q) cout<<q<<endl;
#define all(q) (q).begin(),(q).end()
typedef long long int ll;
typedef unsigned long long int ull;
const int MOD = (int)1e9+7;
const int MAX = 1e6;
#define pi acos(-1)
#define inf 1000000000000000LL
#define FastRead    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int main()
{
    FastRead
    //freopen("output.txt", "w", stdout);
    ll n,t,sum=0,en=-1,last;
    cin>>n>>t;
    while(n--)
    {
        ll a;
        cin>>a;
        if(a>en)
        {
            sum+=t;
            en=a+t;
            last=a;
        }
        else{
            sum+=(a-last);
            en=a+t;
            last=a;
        }
    }
    cout<<sum<<endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--)
#define rrep(i,n) RREP(i,n-1,0)
#define all(v) v.begin(), v.end()
const int inf = 1e9+7;
const ll longinf = 1LL<<60;
const ll mod = 1e9+7;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int N;
  string s, t;
  cin >> N >> s >> t;
  for(int l=N; l<=2*N; l++) {
    string S(l, ' ');
    rep(i, N) S[i] = s[i];
    bool ok = true;
    rep(i, N) if(S[l-N+i] != ' ' && S[l-N+i] != t[i]) ok = false;
    if(ok) {
      cout << l << "\n";
      return 0;
    }
  }
  return 0;
}


#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif

#include <bits/stdc++.h>

using namespace std;

mt19937 mrand(random_device{} ());

int rnd(int x) {
  return mrand() % x;
}

typedef long double ld;
typedef long long ll;

#ifdef DEBUG
#define eprintf(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
#else
#define eprintf(...) ;
#endif

#define pb push_back
#define mp make_pair
#define sz(x) ((int) (x).size())
#define TASK "text"

const int inf = (int) 1.01e9;
const ld eps = 1e-9;
const ld pi = acos((ld) -1.0);

const int mod = (int) 1e9 + 7;

void add(int &x, int y) {
  if ((x += y) >= mod) {
    x -= mod;
  }
}

int mult(int x, int y) {
  return (long long) x * y % mod;
}

int myPower(int x, int pw) {
  int res = 1;
  for (; pw; pw >>= 1) {
    if (pw & 1) {
      res = mult(res, x);
    }
    x = mult(x, x);
  }
  return res;
}

void precalc() {
}

const int maxn = (int) 1e5 + 10;
int table[maxn][3];
int n;

int read() {
  if (scanf("%d", &n) < 1) {
    return 0;
  }
  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < n; ++j) {
      scanf("%d", table[j] + i);
    }
  }
  return 1;
}

int a[maxn];
int xr[maxn];

int used[maxn];

void solve() {
  for (int i = 0; i < n; ++i) {
    if (abs(table[i][1] - table[i][0]) != 1 || abs(table[i][2] - table[i][1]) != 1) {
      printf("No\n");
      return;
    }
    a[i] = (table[i][0] - 1) / 3;
    xr[i] = (table[i][0] > table[i][2]);
  }

  for (int i = 0; i < n; ++i) {
    used[i] = 0;
  }
  int whole[2] = {(((n + 1) / 2) & 1), ((n / 2) & 1)};
  for (int i = 0; i < n; ++i) {
    if ((a[i] & 1) != (i & 1)) {
      printf("No\n");
      return;
    }
    whole[!(i & 1)] ^= xr[i];

    if (!used[i]) {
      whole[i & 1] ^= 1;
      for (int x = i; !used[x]; x = a[x]) {
        used[x] = 1;
      }
    }
  }
  if (whole[0] || whole[1]) {
    printf("No\n");
  } else {
    printf("Yes\n");
    //printf("No\n");
  }
}

int main() {
  precalc();
#ifdef LOCAL
  freopen(TASK ".out", "w", stdout);
  assert(freopen(TASK ".in", "r", stdin));
#endif

  while (1) {
    if (!read()) {
      break;
    }
    solve();
#ifdef DEBUG
    eprintf("Time %.2f\n", (double) clock() / CLOCKS_PER_SEC);
#endif
  }
  return 0;
}