Problem:
大きさが異なる n 個のコップと 3 つのトレイ（お盆）A，B，C があり，それらのコップは 3 つのトレイの上にそれぞれ何個かずつ一山に重ねて置かれている．ただし，どのトレイにおいても，そのトレイの中で一番小さいコップが一番下に， 2 番目に小さいコップがその上に， 3 番目に小さいコップがその上にと，小さい順に伏せて重ねてある．例えば，下図の右側は， n = 5 個のコップがトレイ A，B，C にそれぞれ 2 個，0 個，3 個重ねて置かれている状態を示している．
このように，コップの初期状態が与えられたとき，次の規則 1 〜 3 を守りながら，すべてのコップを A または C のどちらかのトレイに移動させるには何回移動を行えばよいかを求めたい．
（規則 1） 1 回に 1 つのコップだけを移動させることができる．それは，そのトレイにあるコップの中で一番上のコップ（つまり，一番大きいコップ）である．
（規則 2）大きいコップの上に小さいコップを重ねてはいけない．
（規則 3）コップ 1 個の直接移動は，トレイ A から B，B から A，B から C，C から B のみが許され， A から C への直接移動や C から A への直接移動は許されない．
n 個のコップの初期状態と整数 m が与えられたとき， m 回以内の移動で， A または C のどちらかのトレイにすべてのコップをまとめて重ねることができるかどうかを判定し，可能な場合には移動回数の最小値を，不可能な場合には -1 を出力するプログラムを作成しなさい．
入力ファイルの 1 行目には， n と m がこの順に空白を区切り文字として書いてある． 1 ≦ n ≦ 15 であり， 1 ≦ m ≦ 15000000 である． 2 行目，3 行目，4 行目には， 1 から n までの整数を何個かずつ 3 つのグループに分けて，それぞれのグループ内で小さい順（昇順）に並べたものが書いてある．ただし，各行の先頭（それらの整数の前）には，それらの個数が書いてある． 2 行目に書かれている整数（先頭の 1 つを除く）はトレイ A の上に重ねられている各コップの大きさを表す．同様に， 3 行目に書かれている整数（先頭の 1 つを除く）はトレイ B の上に重ねられている各コップの大きさを表し， 4 行目に書かれている整数（先頭の１つを除く）はトレイ C の上に重ねられている各コップの大きさを表す．
入力例１
入力例２
入力例３
入力例４
3 10
4 20
2 5
3 3
0
2 1 2
2 1 2
0
1 1
1 3
0
1 1
2 2 3
1 4
0
2 2 3
出力例１
出力例２
出力例３
出力例４
9
3
0
-1
入力
入力は複数のデータセットからなる．n, m がともに 0 のとき入力が終了する．データセットの数は 5 を超えない．
出力
データセットごとに、移動回数または -1 を１行に出力する．
入力例
3 10
0
1 1
2 2 3
4 20
2 1 2
1 3
1 4
2 5
2 1 2
0
0
3 3
0
1 1
2 2 3
0 0
出力例
9
3
0
-1
各データセットの出力（移動回数または -1）の後に改行を入れること．
上記問題文と自動審判に使われるデータは、
情報オリンピック日本委員会
が作成し公開している問題文と採点用テストデータです。

Submitted solutions:

code_snippet: //
//  main.cpp
//  kyopro
//
//  Created by nandk on 2025/07/26.
//
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
using namespace std;
using ll = long long;

vector<pair<int, int>> direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

long long power3(int n) {
  long long ret = 1;
  for (int i = 0; i < n; i++)
    ret *= 3;
  return ret;
}

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

    vector<vector<int>> cup(3);
    for (auto &v : cup) {
      int k;
      cin >> k;
      v.resize(k);
      for (int i = 0; i < k; i++)
        cin >> v[i];
    }

    long long statesize = power3(n);

    vector<long long> distance(statesize, 2e18);
    long long pos = 0;
    for (int i = 0; i < 3; i++) {
      for (int j : cup[i]) {
        pos += power3(j - 1) * i;
      }
    }
    distance[pos] = 0;
    queue<long long> que;
    que.emplace(pos);

    while (!que.empty()) {
      auto pos = que.front();
      que.pop();

      vector<int> top(3, 0);
      for (int i = 0; i < n; i++) {
        int tray = (pos / power3(i)) % 3;
        top[tray] = max(top[tray], i + 1);
      }

      for (int from = 0; from < 3; from++) {
        for (int to = 0; to < 3; to++) {
          if (abs(from - to) == 1 && top[from] > top[to]) {
            long long nex =
                pos - from * power3(top[from] - 1) + to * power3(top[from] - 1);
            if (distance[nex] > distance[pos] + 1) {
              distance[nex] = distance[pos] + 1;
              que.push(nex);
            }
          }
        }
      }
    }
    long long Answer = min(distance[0], distance[power3(n) - 1]);
    if (Answer > m)
      cout << -1 << endl;
    else
      cout << Answer << endl;
  }
}
accuracy: 1
time_ms: 3490
memory_kb: 115072
final_rank: 20

code_snippet: #define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <functional>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <cmath>
#include<sstream>
#include<list>
#include<iomanip>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <bitset>
#include <cassert>
#include <stdlib.h>
#include <stdio.h>
#include <random>
#include <chrono>
using namespace std;
const long long LINF = 3e18 + 7;
const int MAX_N = 5000010;
const int MAX_W = 10002;
const int MAX_ARRAYK = 100000;
double PI = 3.14159265358979323846;
const int INF = 2147483647;
//using ll = long long;

int N, M;

struct NODE {
	vector<int> s1, s2, s3;
	NODE(vector<int> s1, vector<int> s2, vector<int> s3) : s1(s1), s2(s2), s3(s3) {};
	NODE() {};
};

typedef pair<int, int> MOVE;
typedef pair<NODE, MOVE> P;

bool used[200000000];

int main() {

	while (cin >> N >> M) {
		if (N == 0 && M == 0) {
			break;
		}

		NODE first;
		for (int i = 0; i < 3; i++) {
			int c;
			cin >> c;
			vector<int> s;
			s.push_back(0);
			for (int j = 0; j < c; j++) {
				int a;
				cin >> a;
				s.push_back(a);
			}
			if (i == 0) {
				first.s1 = s;
			}
			if (i == 1) {
				first.s2 = s;
			}
			if (i == 2) {
				first.s3 = s;
			}
		}

		vector<int> target;
		for (int i = 0; i <= N; i++) {
			target.push_back(i);
		}
		queue<P> que;
		MOVE move = MOVE(0, -1);
		que.push(P(first, move));

		while (!que.empty()) {
			NODE n = que.front().first;
			int c = que.front().second.first;
			int t = que.front().second.second;
			que.pop();

			int ff = 0;
			for (int i = 0; i < n.s1.size(); i++) {
				ff += (1 << n.s1[i]);
			}
			for (int i = 0; i < n.s2.size(); i++) {
				ff += (1 << n.s2[i]) * 2;
			}
			if (used[ff]) {
				continue;
			}

			if (c > M) {
				cout << -1 << endl;
				break;
			}

			if (n.s1 == target) {
				cout << c << endl;
				break;
			}
			if (n.s3 == target) {
				cout << c << endl;
				break;
			}

			if (n.s1.back() > n.s2.back() && t != 1) {
				vector<int> s1 = n.s1;
				s1.pop_back();

				vector<int> s2 = n.s2;
				s2.push_back(n.s1.back());

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;
				que.push(P(NODE(s1, s2, n.s3), MOVE(c + 1, 0)));
			}
			if (n.s2.back() > n.s1.back() && t != 0) {
				vector<int> s1 = n.s1;
				s1.push_back(n.s2.back());
				
				vector<int> s2 = n.s2;
				s2.pop_back();

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;
				que.push(P(NODE(s1, s2, n.s3), MOVE(c + 1, 1)));

			}
			if (n.s2.back() > n.s3.back() && t != 3) {
				vector<int> s1 = n.s1;
				vector<int> s2 = n.s2;
				s2.pop_back();

				vector<int> s3 = n.s3;
				s3.push_back(n.s2.back());

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(n.s1, s2, s3), MOVE(c + 1, 2)));

			}
			if (n.s3.back() > n.s2.back() && t != 2) {
				vector<int> s1 = n.s1;
				vector<int> s2 = n.s2;
				s2.push_back(n.s3.back());
				
				vector<int> s3 = n.s3;
				s3.pop_back();

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(n.s1, s2, s3), MOVE(c + 1, 3)));
			}


		}
	}
	

	return 0;
}
accuracy: 1
time_ms: 560
memory_kb: 3452
final_rank: 6

code_snippet: #define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <functional>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <cmath>
#include<sstream>
#include<list>
#include<iomanip>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <bitset>
#include <cassert>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
const int INF = 1000000000;
const long long LINF = 3e18 + 7;
const int MAX_N = 500010;
const int MAX_W = 10002;
const int MAX_ARRAYK = 100000;
double PI = 3.14159265358979323846;
//using ll = long long;


// https://emtubasa.hateblo.jp/entry/2018/08/18/113548
// https://ebisuke33.hatenablog.com/entry/antbook-aoj0503
// https://www.techiedelight.com/ja/check-two-vectors-equal-cpp/

int N, M;

struct NODE {
	vector<int> s1, s2, s3;
	NODE(vector<int> s1, vector<int> s2, vector<int> s3) : s1(s1), s2(s2), s3(s3) {};
	NODE() {};
};

typedef pair<int, int> MOVE;

typedef pair<NODE, MOVE> P;

bool used[200000000];

int main() {

	while (cin >> N >> M) {
		if (N == 0 && M == 0) {
			break;
		}

		NODE first;
		for (int i = 0; i < 3; i++) {
			int c;
			cin >> c;
			vector<int> s;
			s.push_back(0);
			for (int j = 0; j < c; j++) {
				int a;
				cin >> a;
				s.push_back(a);
			}
			if (i == 0) {
				first.s1 = s;
			}
			if (i == 1) {
				first.s2 = s;
			}
			if (i == 2) {
				first.s3 = s;
			}
		}

		vector<int> target;
		for (int i = 0; i <= N; i++) {
			target.push_back(i);
		}

		queue<P> que;
		MOVE move = MOVE(0, -1);
		que.push(P(first, move));

		while (!que.empty()) {
			NODE n = que.front().first;
			int c = que.front().second.first;
			int t = que.front().second.second;
			que.pop();

			int ff = 0;
			for (int i = 0; i < n.s1.size(); i++) {
				ff += (1 << n.s1[i]);
			}
			for (int i = 0; i < n.s2.size(); i++) {
				ff += (1 << n.s2[i]) * 2;
			}
			if (used[ff]) {
				continue;
			}

			if (c > M) {
				cout << -1 << endl;
				break;
			}

			if (n.s1 == target) {
				cout << c << endl;
				break;
			}
			if (n.s3 == target) {
				cout << c << endl;
				break;
			}
			if (n.s1[n.s1.size() - 1] > n.s2[n.s2.size() - 1] && t != 1) {
				
				vector<int> s1;
				for (int i = 0; i < n.s1.size() - 1; i++) {
					s1.push_back(n.s1[i]);
				}
				vector<int> s2 = n.s2;
				
				s2.push_back(n.s1[n.s1.size() - 1]);
				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(s1, s2, n.s3), MOVE(c + 1, 0)));
			}
			if (n.s2[n.s2.size() - 1] > n.s1[n.s1.size() - 1] && t != 0) {

				vector<int> s1 = n.s1;
				s1.push_back(n.s2[n.s2.size() - 1]);
				vector<int> s2;
				for (int i = 0; i < n.s2.size() - 1; i++) {
					s2.push_back(n.s2[i]);
				}

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(s1, s2, n.s3), MOVE(c + 1, 1)));
			}
			if (n.s2[n.s2.size() - 1] > n.s3[n.s3.size() - 1] && t != 3) {
				vector<int> s1 = n.s1;
				vector<int> s2;
				for (int i = 0; i < n.s2.size() - 1; i++) {
					s2.push_back(n.s2[i]);
				}
				vector<int> s3 = n.s3;
				s3.push_back(n.s2[n.s2.size() - 1]);

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(n.s1, s2, s3), MOVE(c + 1, 2)));
			}
			if (n.s3.at(n.s3.size() - 1) > n.s2.at(n.s2.size() - 1) && t != 2) {
				vector<int> s1 = n.s1;
				vector<int> s2 = n.s2;
				s2.push_back(n.s3[n.s3.size() - 1]);
				vector<int> s3;
				for (int i = 0; i < n.s3.size() - 1; i++) {
					s3.push_back(n.s3[i]);
				}

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(n.s1, s2, s3), MOVE(c + 1, 3)));
			}
			

		}

	}


	return 0;
}
accuracy: 1
time_ms: 680
memory_kb: 3476
final_rank: 8

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

// 状態をlong longにエンコード（2ビット×15）
long long encode(const vector<int>& pos, int n) {
    long long res = 0;
    for (int i = 0; i < n; ++i) {
        res |= (long long)pos[i] << (2 * i);
    }
    return res;
}

// デコード：long longを状態に戻す
vector<int> decode(long long s, int n) {
    vector<int> res(n);
    for (int i = 0; i < n; ++i) {
        res[i] = (s >> (2 * i)) & 3;
    }
    return res;
}

// ゴール状態の判定
bool is_goal(const vector<int>& pos, int n) {
    int t = pos[0];
    if (t != 0 && t != 2) return false;
    for (int i = 1; i < n; ++i) {
        if (pos[i] != t) return false;
    }
    return true;
}

int solve(int n, int m, vector<int> pos) {
    long long start = encode(pos, n);

    unordered_map<long long, int> dist;
    queue<long long> q;

    dist[start] = 0;
    q.push(start);

    while (!q.empty()) {
        long long cur = q.front(); q.pop();
        int d = dist[cur];

        if (d > m) continue;

        vector<int> p = decode(cur, n);

        if (is_goal(p, n)) {
            return d;
        }

        // 各トレイの一番上のコップ（=最大番号）
        vector<int> top(3, -1);
        for (int i = n - 1; i >= 0; --i) {
            if (top[p[i]] == -1) {
                top[p[i]] = i;
            }
        }

        // 移動：A<->B, B<->C のみ許可
        for (int from : {0, 1, 2}) {
            if (top[from] == -1) continue;

            for (int to : {0, 1, 2}) {
                if (abs(from - to) != 1) continue; // A-Cは禁止

                if (top[to] == -1 || top[from] > top[to]) {
                    vector<int> np = p;
                    np[top[from]] = to;
                    long long nxt = encode(np, n);

                    if (!dist.count(nxt)) {
                        dist[nxt] = d + 1;
                        q.push(nxt);
                    }
                }
            }
        }
    }

    return -1;
}

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

        vector<int> pos(n);
        for (int tray = 0; tray < 3; ++tray) {
            int k; cin >> k;
            for (int j = 0; j < k; ++j) {
                int x; cin >> x;
                pos[x - 1] = tray;
            }
        }

        cout << solve(n, m, pos) << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 900
memory_kb: 110420
final_rank: 13

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

int main(){
  while(true){
    int n, m; cin>>n>>m;
    if(!n && !m) return 0;
    int a; cin>>a;
    vector<int> va(a + 1, 0);
    for(int i = 0; i < a; i++) cin>>va[i + 1];
    int b; cin>>b;
    vector<int> vb(b + 1, 0);
    for(int i = 0; i < b; i++) cin>>vb[i + 1];
    int c; cin>>c;
    vector<int> vc(c + 1, 0);
    for(int i = 0; i < c; i++) cin>>vc[i + 1];

    vector<int> t;
    for(int i = 0; i <= n; i++) t.push_back(i);

    queue<tuple<vector<int>, vector<int>, vector<int>, int, int>> que;
    que.push(make_tuple(va, vb, vc, 0, -1));
    while(!que.empty()){
      vector<int> x, y, z;
      int k, l;
      tie(x, y, z, k, l) = que.front();
      que.pop();

      if(k > m){
        cout << "-1" << endl;
        break;
      }
      if(t == x || t == z){
        cout << k << endl;
        break;
      }

      if(!x.empty() && !y.empty() && x.back() > y.back() && l != 0){
        vector<int> t1, t2;
        t1 = x;
        t2 = y;
        t2.push_back(t1.back());
        t1.pop_back();
        que.push(make_tuple(t1, t2, z, k + 1, 1));
      }
      if(!x.empty() && !y.empty() && x.back() < y.back() && l != 1){
        vector<int> t1, t2;
        t1 = x;
        t2 = y;
        t1.push_back(t2.back());
        t2.pop_back();
        que.push(make_tuple(t1, t2, z, k + 1, 0));
      }
      if(!y.empty() && !z.empty() && y.back() > z.back() && l != 2){
        vector<int> t1, t2;
        t1 = y;
        t2 = z;
        t2.push_back(t1.back());
        t1.pop_back();
        que.push(make_tuple(x, t1, t2, k + 1, 3));
      }
      if(!y.empty() && !z.empty() && y.back() < z.back() && l != 3){
        vector<int> t1, t2;
        t1 = y;
        t2 = z;
        t1.push_back(t2.back());
        t2.pop_back();
        que.push(make_tuple(x, t1, t2, k + 1, 2));
      }
    }
  }
}
accuracy: 1
time_ms: 390
memory_kb: 3356
final_rank: 4

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


int main() {
    while(true){
      int n, m; cin>>n>>m;
      if(!n && !m) return 0;
      int a; cin>>a;
      vector<int> na(a + 1);
      for(int i = 0; i < a; i++) cin>>na[i + 1];
      int b; cin>>b;
      vector<int> nb(b + 1);
      for(int i = 0; i < b; i++) cin>>nb[i + 1];
      int c; cin>>c;
      vector<int> nc(c + 1);
      for(int i = 0; i < c; i++) cin>>nc[i + 1];
      na[0] = nb[0] = nc[0] = 0;
      queue<tuple<vector<int>, vector<int>, vector<int>, int, int>> que;
      que.push(make_tuple(na, nb, nc, 0, -1));
      vector<int> t;
      for(int i = 0; i <= n; i++) t.push_back(i);

      while(!que.empty()){
        vector<int> x, y, z;
        int k, l;
        tie(x, y, z, k, l) = que.front();
        que.pop();
        if(k > m){
          cout << "-1" << endl;
          break;
        }
        if(t == x || t == z){
          cout << k << endl;
          break;
        }
        if(!x.empty() && !y.empty() && x.back() > y.back() && l != 1){
          vector<int> t1, t2;
          t1 = x;
          t2 = y;
          t2.push_back(t1.back());
          t1.pop_back();
          que.push(make_tuple(t1, t2, z, k + 1, 0));
        }
        if(!x.empty() && !y.empty() && x.back() < y.back() && l != 0){
          vector<int> t1, t2;
          t1 = x;
          t2 = y;
          t1.push_back(t2.back());
          t2.pop_back();
          que.push(make_tuple(t1, t2, z, k + 1, 1));
        }
        if(!z.empty() && !y.empty() && z.back() > y.back() && l != 3){
          vector<int> t1, t2;
          t1 = y;
          t2 = z;
          t1.push_back(t2.back());
          t2.pop_back();
          que.push(make_tuple(x, t1, t2, k + 1, 2));
        }
        if(!z.empty() && !y.empty() && z.back() < y.back() && l != 2){
          vector<int> t1, t2;
          t1 = y;
          t2 = z;
          t2.push_back(t1.back());
          t1.pop_back();
          que.push(make_tuple(x, t1, t2, k + 1, 3));
        }
      }
    }
    return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 3352
final_rank: 3

code_snippet: #define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <functional>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <cmath>
#include<sstream>
#include<list>
#include<iomanip>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <bitset>
#include <cassert>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
const int INF = 100000000;
const long long LINF = 3e18 + 7;
const int MAX_N = 2000010;
const int MAX_W = 10002;
const int MAX_ARRAYK = 100000;
double PI = 3.14159265358979323846;
//using ll = long long;


// https://emtubasa.hateblo.jp/entry/2018/08/18/113548
// https://ebisuke33.hatenablog.com/entry/antbook-aoj0503
// https://www.techiedelight.com/ja/check-two-vectors-equal-cpp/

int N, M;

struct NODE {
	vector<int> s1, s2, s3;
	NODE(vector<int> s1, vector<int> s2, vector<int> s3) : s1(s1), s2(s2), s3(s3) {};
	NODE() {};
};

typedef pair<int, int> MOVE;

typedef pair<NODE, MOVE> P;

bool used[200000000];

int main() {

	while (cin >> N >> M) {
		if (N == 0 && M == 0) {
			break;
		}

		NODE first;
		for (int i = 0; i < 3; i++) {
			int c;
			cin >> c;
			vector<int> s;
			s.push_back(0);
			for (int j = 0; j < c; j++) {
				int a;
				cin >> a;
				s.push_back(a);
			}
			if (i == 0) {
				first.s1 = s;
			}
			if (i == 1) {
				first.s2 = s;
			}
			if (i == 2) {
				first.s3 = s;
			}
		}

		vector<int> target;
		for (int i = 0; i <= N; i++) {
			target.push_back(i);
		}

		queue<P> que;
		MOVE move = MOVE(0, -1);
		que.push(P(first, move));

		while (!que.empty()) {
			NODE n = que.front().first;
			int c = que.front().second.first;
			int t = que.front().second.second;
			que.pop();

			int ff = 0;
			for (int i = 0; i < n.s1.size(); i++) {
				ff += (1 << n.s1[i]);
			}
			for (int i = 0; i < n.s2.size(); i++) {
				ff += (1 << n.s2[i]) * 2;
			}
			if (used[ff]) {
				continue;
			}

			if (c > M) {
				cout << -1 << endl;
				break;
			}

			if (n.s1 == target) {
				cout << c << endl;
				break;
			}
			if (n.s3 == target) {
				cout << c << endl;
				break;
			}
			if (n.s1[n.s1.size() - 1] > n.s2[n.s2.size() - 1] && t != 1) {

				vector<int> s1;
				for (int i = 0; i < n.s1.size() - 1; i++) {
					s1.push_back(n.s1[i]);
				}
				vector<int> s2 = n.s2;

				s2.push_back(n.s1[n.s1.size() - 1]);
				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(s1, s2, n.s3), MOVE(c + 1, 0)));
			}
			if (n.s2[n.s2.size() - 1] > n.s1[n.s1.size() - 1] && t != 0) {

				vector<int> s1 = n.s1;
				s1.push_back(n.s2[n.s2.size() - 1]);
				vector<int> s2;
				for (int i = 0; i < n.s2.size() - 1; i++) {
					s2.push_back(n.s2[i]);
				}

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(s1, s2, n.s3), MOVE(c + 1, 1)));
			}
			if (n.s2[n.s2.size() - 1] > n.s3[n.s3.size() - 1] && t != 3) {
				vector<int> s1 = n.s1;
				vector<int> s2;
				for (int i = 0; i < n.s2.size() - 1; i++) {
					s2.push_back(n.s2[i]);
				}
				vector<int> s3 = n.s3;
				s3.push_back(n.s2[n.s2.size() - 1]);

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(n.s1, s2, s3), MOVE(c + 1, 2)));
			}
			if (n.s3.at(n.s3.size() - 1) > n.s2.at(n.s2.size() - 1) && t != 2) {
				vector<int> s1 = n.s1;
				vector<int> s2 = n.s2;
				s2.push_back(n.s3[n.s3.size() - 1]);
				vector<int> s3;
				for (int i = 0; i < n.s3.size() - 1; i++) {
					s3.push_back(n.s3[i]);
				}

				int f = 0;
				for (int i = 1; i < s1.size(); i++) {
					f += (1 << s1[i]);
				}
				for (int i = 1; i < s2.size(); i++) {
					f += (1 << s2[i]) * 2;
				}
				used[f] = true;

				que.push(P(NODE(n.s1, s2, s3), MOVE(c + 1, 3)));
			}


		}

	}


	return 0;
}
accuracy: 1
time_ms: 680
memory_kb: 3376
final_rank: 7

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

int N,M;
vector<ll> TR;
ll tr(vector<stack<int>> A){
    ll rs=0;
    rep(i,3){
        while(A[i].size()>0){
            int p=A[i].top();
            A[i].pop();
            if(p>0)rs+=TR[p-1]*i;
        }
    }
    return rs;
}
vector<stack<int>> tr(ll x){
    vector<stack<int>> rs(3);
    rep(i,3)rs[i].push(-1);
    rep(i,N){
        rs[x%3].push(i+1);
        x/=3;
    }
    return rs;
}
vector<array<int,2>> P={{0,1},{1,0},{1,2},{2,1}};
    
ll mv(ll x,ll p){
    vector<int> U(3,-1);
    ll nx=x;
    rep(i,N){
        U[x%3]=i;
        x/=3;
    }    
    if(U[P[p][0]]>U[P[p][1]]){
        if(P[p][0]>P[p][1])nx-=TR[U[P[p][0]]];
        else nx+=TR[U[P[p][0]]];
        return nx;
    }
    else return -1;
}

void solve(int N,int M){
    TR.resize(N+2,1);
    rep(i,N+1)TR[i+1]=TR[i]*3;
    ll A=0;
    for(int i=0;i<3;i++){
        int n;
        cin>>n;
        rep(j,n){
            int a;
            cin>>a;
            A+=TR[a-1]*i;
        }
        
    } 
    unordered_map<ll,int> MP;
    MP[A]=0;
    queue<ll> Q;
    Q.push(A);
    
    int cnt=0;
    while(!Q.empty()){
        ll TA=Q.front();
        Q.pop();
        cnt++;
        if(TA==0||TA==TR[N]-1){
            cout<<MP[TA]<<endl;
            return;
        }
        if(MP[TA]==M)break;
        rep(bb,4){
            ll nx=mv(TA,bb);
            if(nx==-1)continue;
            if(!MP.count(nx))MP[nx]=1e9;
            if(MP[nx]>MP[TA]+1){
                MP[nx]=MP[TA]+1;
                Q.push(nx);
            }
        }
    }
    cout<<-1<<endl;
}

int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    while(cin>>N>>M,N!=0)solve(N,M);
    
}
accuracy: 1
time_ms: 800
memory_kb: 110300
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long double db;
typedef long long ll;
typedef  __int128 i128;
typedef pair<int,int>P;
typedef pair<ll,ll>Pll;
mt19937 rnd(time(0));
const ll mod=998244353;
const ll inf=1<<30;
const int N=1e5+5;
bool ok=true;
int dx[8]={0,0,1,-1,1,1,-1,-1};
int dy[8]={1,-1,0,0,1,-1,1,-1};
struct Edge{
    vector<vector<int>>A;
    int y,x;
};
void solve(){
    int n,m;
    while(cin >> n >> m){
        if(n==0&&m==0) break;
        vector<vector<int>>a(3);
        unordered_map<string,int>mp;
        int ans=m+5;
        int D=0;
        for(int i=0;i<3;i++){
            int k;
            cin >> k;
            D+=k;
            for(int j=0;j<k;j++){
                int x;
                cin >> x;
                a[i].push_back(x);
            }
            sort(a[i].begin(),a[i].end());
        }
        assert(D==n);
        if(n==0){
            cout << 0 << "\n";
            continue;
        }
        queue<Edge>que;
        que.push({a,0,0});
        vector<vector<int>>cur;   //A->B:1 B->A:2 B->C:3 C->B:4  
        while(!que.empty()){
            auto [x,y,z]=que.front();
            //cerr << y << " " << z << "\n";
            que.pop();
            if(x[0].size()==n||x[2].size()==n){
                ans=min(ans,y);
                continue;
            }
            if(y>=min(m,ans)) continue;
            if(!x[1].empty()){
                if(z!=1&&(x[0].empty()||x[1].back()>x[0].back())){
                    cur=x;
                    cur[0].push_back(x[1].back());
                    cur[1].pop_back();
                    que.push({cur,y+1,2});
                }
                if(z!=4&&(x[2].empty()||x[1].back()>x[2].back())){
                    cur=x;
                    cur[2].push_back(x[1].back());
                    cur[1].pop_back();
                    que.push({cur,y+1,3});
                }
            }
            if(!x[0].empty()){
                if(z!=2&&(x[1].empty()||x[0].back()>x[1].back())){
                    cur=x;
                    cur[1].push_back(x[0].back());
                    cur[0].pop_back();
                    que.push({cur,y+1,1});
                }
            }
            if(!x[2].empty()){
                if(z!=3&&(x[1].empty()||x[2].back()>x[1].back())){
                    cur=x;
                    cur[1].push_back(x[2].back());
                    cur[2].pop_back();
                    que.push({cur,y+1,4});
                }
            }
        }
        //cerr << ans << "\n";
        cout << (ans<=m?ans:-1) << "\n";
    }
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cout << fixed << setprecision(2);
    int T = 1;
    //cin >> T;
    while (T--) {
        solve();
    }
    return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 3136
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long double db;
typedef long long ll;
typedef  __int128 i128;
typedef pair<int,int>P;
typedef pair<ll,ll>Pll;
mt19937 rnd(time(0));
const ll mod=998244353;
const ll inf=1<<30;
const int N=1e5+5;
bool ok=true;
int dx[8]={0,0,1,-1,1,1,-1,-1};
int dy[8]={1,-1,0,0,1,-1,1,-1};
struct Edge{
    vector<vector<int>>A;
    int y,x;
};
void solve(){
    int n,m;
    while(cin >> n >> m){
        if(n==0&&m==0) break;
        vector<vector<int>>a(3);
        unordered_map<string,int>mp;
        int ans=m+5;
        int D=0;
        for(int i=0;i<3;i++){
            int k;
            cin >> k;
            D+=k;
            for(int j=0;j<k;j++){
                int x;
                cin >> x;
                a[i].push_back(x);
            }
            sort(a[i].begin(),a[i].end());
        }
        assert(D==n);
        if(n==0){
            cout << 0 << "\n";
            continue;
        }
        queue<Edge>que;
        que.push({a,0,0});
        vector<vector<int>>cur;   //A->B:1 B->A:2 B->C:3 C->B:4  
        while(!que.empty()){
            auto [x,y,z]=que.front();
            //cerr << y << " " << z << "\n";
            que.pop();
            if(x[0].size()==n||x[2].size()==n){
                ans=min(ans,y);
                break;
            }
            if(y>=min(m,ans)) continue;
            if(!x[1].empty()){
                if(z!=1&&(x[0].empty()||x[1].back()>x[0].back())){
                    cur=x;
                    cur[0].push_back(x[1].back());
                    cur[1].pop_back();
                    que.push({cur,y+1,2});
                }
                if(z!=4&&(x[2].empty()||x[1].back()>x[2].back())){
                    cur=x;
                    cur[2].push_back(x[1].back());
                    cur[1].pop_back();
                    que.push({cur,y+1,3});
                }
            }
            if(!x[0].empty()){
                if(z!=2&&(x[1].empty()||x[0].back()>x[1].back())){
                    cur=x;
                    cur[1].push_back(x[0].back());
                    cur[0].pop_back();
                    que.push({cur,y+1,1});
                }
            }
            if(!x[2].empty()){
                if(z!=3&&(x[1].empty()||x[2].back()>x[1].back())){
                    cur=x;
                    cur[1].push_back(x[2].back());
                    cur[2].pop_back();
                    que.push({cur,y+1,4});
                }
            }
        }
        //cerr << ans << "\n";
        cout << (ans<=m?ans:-1) << "\n";
    }
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cout << fixed << setprecision(2);
    int T = 1;
    //cin >> T;
    while (T--) {
        solve();
    }
    return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 3384
final_rank: 5

code_snippet: #include<iostream>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;

typedef pair<int,int> P;
bool use[15000000];

int main(){
  int n,m,now;

  for(;;){
    cin >> n >> m;
    if(!n && !m)break;

    now = 0;
    for(int i=0;i<3;i++){
      int num;
      cin >> num;
      for(int j=0;j<num;j++){
	int tmp;
	cin >> tmp;
	now += pow(3,tmp-1)*i;
      }
    }

    int lim = pow(3,n);
    for(int i=0;i<lim;i++)use[i] = false;
    use[now] = true;

    int ans = -1;

    queue<P> q;
    q.push(P(now,0));

    while(q.size()){
      P p = q.front();q.pop();
      int s[3] = {-1,-1,-1};
      now = p.first;
      for(int i=1;i<=n;i++){
	s[now%3] = i;
	now/=3;
      }
     
      if( (s[0]<0 && s[1]<0) || (s[1]<0 && s[2]<0) ){
	ans = p.second;
	break;
      }
      if(p.second>m)break;

      int d1[] = {0,1,1,2},d2[] = {1,0,2,1};

      for(int i=0;i<4;i++){
	if(s[d1[i]]>s[d2[i]]){
	  int hoge = pow(3,s[d1[i]]-1);
	  now = p.first - hoge*d1[i] + hoge*d2[i];
	  if(!use[now]){
	    use[now] = true;
	    q.push(P(now,p.second+1));
	  }
	}
      }
    }
    cout << ans << endl;
  }
}
accuracy: 1
time_ms: 310
memory_kb: 18112
final_rank: 9

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


int BFS(stack<int> A, stack<int> B, stack<int> C, int turn, int res = 0) {

   // 探索開始
   while(true) {

      // 移動対象 cup_number 取得
      int a, b, c;
      A.empty() ? a = 0: a = A.top();
      B.empty() ? b = 0: b = B.top();
      C.empty() ? c = 0: c = C.top();
         
      // 探索完了判定
      if(a == b || b == c) return res;

      // a → b へ移動
      if(turn==1 && a>b) {
         B.push(a); A.pop();
         res++; turn = 0;
      }

      // b → a へ移動
      else if(turn==1 && a<b) {
         A.push(b); B.pop();
         res++; turn = 0;
      }

      // b → c へ移動
      else if(turn==0 && b>c) {
         C.push(b); B.pop();
         res++; turn = 1;
      }
      
      // c → b へ移動
      else if(turn==0 && b<c) {
         B.push(c); C.pop();
         res++; turn = 1;
      }
   }
}


int main() {
   
   while(true) {

      // 諸元入力
      int n, m; cin >> n >> m;
      stack<int> SA, SB, SC;
      vector<int> ans(2, 0);

      // データセット判定
      if(n == 0 && m == 0) return 0;

      // データ取得
      for(int i = 0; i < 3; i++) {
         int k; cin >> k;

         for(int j = 0; j < k; j++) {
            int num; cin >> num;
            if(i == 0) SA.push(num);
            if(i == 1) SB.push(num);
            if(i == 2) SC.push(num);
         }
      }
      
      // 移動方向選択（BFS)
      for(int Ph = 0; Ph < 2; Ph++) {
         ans[Ph] = BFS(SA, SB, SC, Ph);
      }
      
      // 結果判定
      int res = min(ans[0], ans[1]);

      // 結果出力
      if(res <= m) cout << res << endl;
      else cout << -1 << endl;
   }
}
accuracy: 1
time_ms: 40
memory_kb: 3008
final_rank: 1

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <iomanip>
#include <climits>
using namespace std;

int powe(int a, int b) {
	int r {1}, c {a};
	while (b) {
		if (b % 2) r *= c;
		c *= c;
		b /= 2;
	}
	return r;
}

int main() {
	int n, m;
	cin >> n >> m;
	while (n || m) {
		int b {};
		map<int, int> mp;
		for (int i = 0; i < 3; ++i) {
			int a;
			cin >> a;
			for (int j = 0; j < a; ++j) {
				int c;
				cin >> c;
				b += i * powe(3, c - 1);
			}
		}
		mp[b] = 0;
		queue<int> q;
		q.push(b);
		while (!q.empty()) {
			int c {q.front()}, e {c}, f0 {-1}, f1 {-1}, f2 {-1}, g;
			for (int i = 0; i < n; ++i) {
				if (e % 3 == 0) f0 = i;
				else if (e % 3 == 1) f1 = i;
				else f2 = i;
				e /= 3;
			}
			if (f1 == -1 && (f2 == -1 || f0 == -1)) {
				if (mp[c] <= m) cout << mp[c] << '\n';
				else cout << "-1\n";
				break;
			}
			q.pop();
			if (f0 < f1) g = c - powe(3, f1);
			else g = c + powe(3, f0);
			if (!mp.count(g)) {
				mp[g] = mp[c] + 1;
				q.push(g);
			}
			if (f1 < f2) g = c - powe(3, f2);
			else g = c + powe(3, f1);
			if (!mp.count(g)) {
				mp[g] = mp[c] + 1;
				q.push(g);
			}
		}
		if (q.empty()) cout << "-1\n";
		cin >> n >> m;
	}
}
accuracy: 1
time_ms: 1510
memory_kb: 120520
final_rank: 17

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>
#include <unordered_set>
#include <functional>
using namespace std;
//using namespace atcoder;
using ll = long long;
using P = pair<int, int>;
#define rep(i, n) for (int i = 0; i < (n); i++)
//void chmin(ll & a, ll b) { a = min(a, b); }
//using mint = modint998244353;

int n, m;
int memo3[16] = { 0,1,3,9,
				27,81,243,729,
				2187,6561,19683,59049,
				177147,531441, 1594323,4782969 };
bool memo[15000000] = { 0 };
int from[4] = { 0,1,1,2 };
int to[4] = { 1,0,2,1 };
struct dish {
	vector<int> v[3];
	int now;
};

dish first;

int solve();
int calc3(dish x);

int main() {
	int a, x;
	while (1) {
		cin >> n >> m;
		if (n + m == 0) break;
		rep(i, 3) {
			cin >> x;
			rep(j, x) {
				cin >> a;
				first.v[i].push_back(a);
			}
		}
		first.now = 0;
		memo[calc3(first)] = 1;
		cout << solve() << endl;
		rep(i, 3) {
			first.v[i].erase(first.v[i].begin(), first.v[i].end());
		}
		rep(i, 15000000) memo[i] = 0;
	}
	return 0;
}

int solve() {
	dish now = first, next;
	bool end = 0;
	int ans = -1;
	queue<dish> qu;
	qu.push(first);
	while (qu.size() > 0 && now.now <= m && !end) {
		now = qu.front();
		qu.pop();
		if (now.v[0].size() == n || now.v[2].size() == n) {
			ans = now.now;
			end = 1;
			break;
		}
		rep(i, 4) {
			int f = from[i], t = to[i];
			next = now;
			if (next.v[f].size() != 0 &&
				(next.v[t].size()==0 ||
				next.v[f][next.v[f].size() - 1] >
				next.v[t][next.v[t].size() - 1])) {
				int x = next.v[f][next.v[f].size() - 1], y;
				next.v[f].pop_back();
				next.v[t].push_back(x);
				++next.now;
				y = calc3(next);
				if (memo[y] == 0) {
					qu.push(next);
					memo[y] = 1;
				}
			}
		}
	}
	return ans;
}


int calc3(dish x) {
	int ans = 0;
	rep(i, 3) {
		rep(j, x.v[i].size()) {
			ans += i * memo3[x.v[i][j]];
		}
	}
	return ans;
}
accuracy: 1
time_ms: 760
memory_kb: 17948
final_rank: 11

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

int n, m;
int memo3[16] = {0,      1,      3,       9,
                 27,     81,     243,     729,
                 2187,   6561,   19683,   59049,
                 177147, 531441, 1594323, 4782969};
bool memo[15000000] = {0};
int from[4] = {0, 1, 1, 2};
int to[4] = {1, 0, 2, 1};
struct dish {
  vector<int> v[3];
  int now;
};
dish first;

int solve();
int calc3(dish x);

int main() {
  int a, x;
  while(1) {
    cin >> n >> m;
    if(n + m == 0) break;
    for(int i = 0; i < 3; ++i) {
      cin >> x;
      for(int j = 0; j < x; ++j) {
        cin >> a;
        first.v[i].push_back(a);
      }
    }
    first.now = 0;
    memo[calc3(first)] = 1;
    cout << solve() << endl;
    for(int i = 0; i < 3; ++i)
      first.v[i].erase(first.v[i].begin(),
                       first.v[i].end());
    for(int i = 0; i < 15000000; ++i) memo[i] = 0;
  }
  return 0;
}

int solve() {
  dish now = first, next;
  bool end = 0;
  int ans = -1;
  queue<dish> qu;
  qu.push(first);
  while(qu.size() > 0 && now.now <= m && !end) {
    now = qu.front();
    qu.pop();
    if(now.v[0].size() == n || now.v[2].size() == n) {
      ans = now.now;
      end = 1;
      break;
    }
    for(int i = 0; i < 4; ++i) {
      int f = from[i], t = to[i];
      next = now;
      if(next.v[f].size() != 0 &&
         (next.v[t].size() == 0 ||
          next.v[f][next.v[f].size() - 1] >
              next.v[t][next.v[t].size() - 1])) {
        int x = next.v[f][next.v[f].size() - 1], y;
        next.v[f].pop_back();
        next.v[t].push_back(x);
        ++next.now;
        y = calc3(next);
        if(memo[y] == 0) {
          qu.push(next);
          memo[y] = 1;
        }
      }
    }
  }
  return ans;
}
int calc3(dish x) {
  int ans = 0;
  for(int i = 0; i < 3; ++i) {
    for(int j = 0; j < x.v[i].size(); ++j)
      ans += i * memo3[x.v[i][j]];
  }
  return ans;
}
accuracy: 1
time_ms: 760
memory_kb: 17788
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
int main() {
    while (true) {
        int n, m;
        cin >> n >> m;
        if (n == 0 && m == 0) break;
        bitset<30> cups;
        queue<pair<int, int>> que;
        set<int> check;
        bitset<30> Agoal;
        bitset<30> Cgoal;
        for (int i = 0; i < 2 * n; i++) {
            if (i % 2 == 0) Agoal[i] = 1;
            Cgoal[i] = 1;
        }
        for (int i = 1; i <= 3; i++) {
            int size;
            cin >> size;
            for (int j = 0; j < size; j++) {
                int num;
                cin >> num;
                num--;
                if (i >= 2) {
                    cups.set(num * 2 + 1);
                }
                if (i % 2 == 1) {
                    cups.set(num * 2);
                }
            }
        }
        que.push({cups.to_ullong(), 0});
        check.insert(cups.to_ullong());
        int ans = -1;
        while (!que.empty() && que.front().second <= m) {
            bitset<30> crt(que.front().first);
            if (crt == Agoal.to_ullong() || crt == Cgoal.to_ullong()) {
                ans = que.front().second;
                break;
            }
            bool flag[3] = {true, true, true};
            for (int i = 14; i >= 0; i--) {
                if (crt[2 * i] == 1 && crt[2 * i + 1] == 1 && flag[2]) {
                    flag[2] = false;
                    if (flag[1]) {
                        crt[2 * i] = 0;
                        if (!check.count(crt.to_ullong())) {
                            que.push({crt.to_ullong(), que.front().second + 1});
                            check.insert(crt.to_ullong());
                        }
                        crt[2 * i] = 1;
                    }
                }
                if (crt[2 * i] == 0 && crt[2 * i + 1] == 1 && flag[1]) {
                    flag[1] = false;
                    if (flag[2]) {
                        crt[2 * i] = 1;
                        if (!check.count(crt.to_ullong())) {
                            que.push({crt.to_ullong(), que.front().second + 1});
                            check.insert(crt.to_ullong());
                        }
                        crt[2 * i] = 0;
                    }
                    if (flag[0]) {
                        crt[2 * i + 1] = 0;
                        crt[2 * i] = 1;
                        if (!check.count(crt.to_ullong())) {
                            que.push({crt.to_ullong(), que.front().second + 1});
                            check.insert(crt.to_ullong());
                        }
                        crt[2 * i + 1] = 1;
                        crt[2 * i] = 0;
                    }
                }
                if (crt[2 * i] == 1 && crt[2 * i + 1] == 0 && flag[0]) {
                    flag[0] = false;
                    if (flag[1]) {
                        crt[2 * i + 1] = 1;
                        crt[2 * i] = 0;
                        if (!check.count(crt.to_ullong())) {
                            que.push({crt.to_ullong(), que.front().second + 1});
                            check.insert(crt.to_ullong());
                        }
                        crt[2 * i + 1] = 0;
                        crt[2 * i] = 1;
                    }
                }
            }
            que.pop();
        }
        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 1340
memory_kb: 120396
final_rank: 16

code_snippet: #line 1 "/opt/library/template.hpp"
#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using i64 = long long;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
using u128 = unsigned __int128;
using f128 = __float128;

template <class T>
constexpr T infty = 0;
template <>
constexpr int infty<int> = 1'000'001'000;
template <>
constexpr ll infty<ll> = ll(infty<int>) * infty<int> * 2;
template <>
constexpr u32 infty<u32> = infty<int>;
template <>
constexpr u64 infty<u64> = infty<ll>;
template <>
constexpr i128 infty<i128> = i128(infty<ll>) * infty<ll>;
template <>
constexpr double infty<double> = infty<ll>;
template <>
constexpr long double infty<long double> = infty<ll>;
#define inf infty<ll>

using pi = pair<ll, ll>;
using vi = vector<ll>;
using vvi = vector<vector<ll>>;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;

#define vv(type, name, h, ...) \
  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...)   \
  vector<vector<vector<type>>> name( \
      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)       \
  vector<vector<vector<vector<type>>>> name( \
      a, vector<vector<vector<type>>>(       \
             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

#define rep1(a) for (ll _ = 0; _ < (ll)(a); ++_)
#define rep2(i, a) for (ll i = 0; i < (ll)(a); ++i)
#define rep3(i, a, b) for (ll i = a; i < (ll)(b); ++i)
#define rep4(i, a, b, c) for (ll i = a; i < (ll)(b); i += (c))
#define rrep1(a) for (ll i = (a)-1; i >= (ll)(0); --i)
#define rrep2(i, a) for (ll i = (a)-1; i >= (ll)(0); --i)
#define rrep3(i, a, b) for (ll i = (b)-1; i >= (ll)(a); --i)
#define rrep4(i, a, b, c) for (ll i = (b)-1; i >= (ll)(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define rrep(...) overload4(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__)

#define all(x) (x).begin(),(x).end()
#define len(x) (ll)(x.size())
#define elif else if
#define bit(x, i) (((x)>>(i))&1)

#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second

#define stoi stoll
#define abs llabs

#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) \
  sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()

ll popcnt(ll x) { return __builtin_popcountll(x); }
ll popcnt(u64 x) { return __builtin_popcountll(x); }
ll popcnt_mod_2(ll x) { return __builtin_parityll(x); }
ll popcnt_mod_2(u64 x) { return __builtin_parityll(x); }
ll topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
ll topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
ll lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
ll lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T floor(T a, T b) {
  return a / b - (a % b && (a ^ b) < 0);
}
template <typename T>
T ceil(T x, T y) {
  return floor(x + y - 1, y);
}
template <typename T>
T bmod(T x, T y) {
  return x - y * floor(x, y);
}
template <typename T>
pair<T, T> divmod(T x, T y) {
  T q = floor(x, y);
  return {q, x - q * y};
}

template<typename T> T SUM(const vector<T> &A) {
  T s = 0; for (auto &&a: A) s += a;
  return s;
}

template <typename T>
T POP(queue<T> &que) {
  T a = que.front();
  que.pop();
  return a;
}
template <typename T>
T POP(deque<T> &que) {
  T a = que.front();
  que.pop_front();
  return a;
}
template <typename T>
T POP(pq<T> &que) {
  T a = que.top();
  que.pop();
  return a;
}
template <typename T>
T POP(pqg<T> &que) {
  T a = que.top();
  que.pop();
  return a;
}
template <typename T>
T POP(vc<T> &que) {
  T a = que.back();
  que.pop_back();
  return a;
}

template <typename F>
ll binary_search(F check, ll ok, ll ng, bool check_ok = true) {
  if (check_ok) assert(check(ok));
  while (abs(ok - ng) > 1) {
    auto x = (ng + ok) / 2;
    (check(x) ? ok : ng) = x;
  }
  return ok;
}
template <typename F>
f128 binary_search_real(F check, f128 ok, f128 ng, ll iter = 100) {
  rep(iter) {
    f128 x = (ok + ng) / 2;
    (check(x) ? ok : ng) = x;
  }
  return (ok + ng) / 2;
}

// ? は -1
vc<int> s_to_vi(const string &S, char first_char) {
  vc<int> A(S.size());
  rep(i, S.size()) { A[i] = (S[i] != '?' ? S[i] - first_char : -1); }
  return A;
}

template <typename T, typename U>
vc<T> cumsum(vc<U> &A, ll off = 1) {
  ll N = A.size();
  vc<T> B(N + 1);
  rep(i, N) { B[i + 1] = B[i] + A[i]; }
  if (off == 0) B.erase(B.begin());
  return B;
}

// stable sort
template <typename T>
vi argsort(const vector<T> &A) {
  vi ids(len(A));
  iota(all(ids), 0);
  sort(all(ids),
       [&](ll i, ll j) { return (A[i] == A[j] ? i < j : A[i] < A[j]); });
  return ids;
}

// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vi &I) {
  vc<T> B(len(I));
  rep(i, len(I)) B[i] = A[I[i]];
  return B;
}

template<typename T> inline bool chmax(T &a, T b) {return ((a<b)?(a=b,true):(false));}
template<typename T> inline bool chmin(T &a, T b) {return ((a>b)?(a=b,true):(false));}

inline void wt(const char c) { cout << c; }
inline void wt(const string s) { cout << s; }
inline void wt(const char *s) { cout << s; }

template <typename T>
void wt_integer(T x) {
  cout << (x);
}
template <typename T>
void wt_real(T x) {
  cout << fixed << setprecision(15) << (long double)(x);
}
template <typename T>
void wt_integer128(T x) {
  char buf[64];
  char *d = end(buf);
  d--; *d = '\0';
  __uint128_t tmp = ((x < 0)? -x : x);
  do {
    d--; *d = char(tmp%10 + '0'); tmp /= 10;
  } while (tmp);
  if (x < 0) {
    d--; *d = '-';
  }
  cout << d;
}

inline void wt(int x) { wt_integer(x); }
inline void wt(ll x) { wt_integer(x); }
inline void wt(i128 x) { wt_integer128(x); }
inline void wt(u32 x) { wt_integer(x); }
inline void wt(u64 x) { wt_integer(x); }
inline void wt(u128 x) { wt_integer128(x); }
inline void wt(double x) { wt_real(x); }
inline void wt(long double x) { wt_real(x); }
inline void wt(f128 x) { wt_real(x); }

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

void print() { wt('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
  wt(head);
  if (sizeof...(Tail)) wt(' ');
  print(forward<Tail>(tail)...);
}

void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
void onez(bool t = 1) { print(t ? 1 : 0); }
#define endl '\n'
#define dump(x) {cerr << #x " = " << x << '\n';}
#line 2 "main.cpp"

int solve();
int main() {
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  while (!solve()) {}
  return 0;
}

int solve() {
  int n, m, s, a;
  cin >> n >> m;
  if (n == 0 and m == 0) return 1;
  // 適当なのでハッシュ値が被る可能性があるが、通ったのでよし
  auto hash_state = [&](const vc<stack<int>>& v) -> u64 {
    u64 h = 0;
    for (auto i : v) {
      h *= 31;
      h += i.size();
      while (!i.empty()) {
        h *= 31;
        h += i.top();
        i.pop();
      }
    }
    return h;
  };
  unordered_map<u64, int> memo;
  vc<stack<int>> t(3);
  int nums = 0;
  rep(i, 3) {
    cin >> s;
    nums += s;
    rep(s) {
      cin >> a;
      t[i].push(a);
    }
  }
  rep(i, 0, 3, 2) {
    if (len(t[i]) == nums) {
      print(0);
      return 0;
    }
  }
  queue<pair<vc<stack<int>>, int>> Q;
  memo[hash_state(t)] = 0;
  Q.emplace(mp(t, 0));
  while (!Q.empty()) {
    auto [v, d] = POP(Q);
    if (d >= m) break;
    rep(i, 3) {
      if (v[i].empty()) continue;
      rep(k, -1, 1+1, 2) {
        int j = i + k;
        if (j < 0 || j >= 3) continue;
        if (v[j].empty() or (v[i].top() > v[j].top())) {
          t = v;
          t[j].push(v[i].top());
          if ((j != 1) and (len(t[j]) == nums)) {
            print(d+1);
            return 0;
          }
          t[i].pop();
          u64 h = hash_state(t);
          if (memo.count(h)) continue;
          memo[h] = d+1;
          Q.emplace(mp(t, d+1));
        }
      }
    }
  }
  print(-1);
  return 0;
}
accuracy: 1
time_ms: 2430
memory_kb: 110356
final_rank: 19

code_snippet: #line 1 "/opt/library/template.hpp"
#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using i64 = long long;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
using u128 = unsigned __int128;
using f128 = __float128;

template <class T>
constexpr T infty = 0;
template <>
constexpr int infty<int> = 1'000'001'000;
template <>
constexpr ll infty<ll> = ll(infty<int>) * infty<int> * 2;
template <>
constexpr u32 infty<u32> = infty<int>;
template <>
constexpr u64 infty<u64> = infty<ll>;
template <>
constexpr i128 infty<i128> = i128(infty<ll>) * infty<ll>;
template <>
constexpr double infty<double> = infty<ll>;
template <>
constexpr long double infty<long double> = infty<ll>;
#define inf infty<ll>

using pi = pair<ll, ll>;
using vi = vector<ll>;
using vvi = vector<vector<ll>>;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;

#define vv(type, name, h, ...) \
  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...)   \
  vector<vector<vector<type>>> name( \
      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)       \
  vector<vector<vector<vector<type>>>> name( \
      a, vector<vector<vector<type>>>(       \
             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

#define rep1(a) for (ll _ = 0; _ < (ll)(a); ++_)
#define rep2(i, a) for (ll i = 0; i < (ll)(a); ++i)
#define rep3(i, a, b) for (ll i = a; i < (ll)(b); ++i)
#define rep4(i, a, b, c) for (ll i = a; i < (ll)(b); i += (c))
#define rrep1(a) for (ll i = (a)-1; i >= (ll)(0); --i)
#define rrep2(i, a) for (ll i = (a)-1; i >= (ll)(0); --i)
#define rrep3(i, a, b) for (ll i = (b)-1; i >= (ll)(a); --i)
#define rrep4(i, a, b, c) for (ll i = (b)-1; i >= (ll)(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define rrep(...) overload4(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__)

#define all(x) (x).begin(),(x).end()
#define len(x) (ll)(x.size())
#define elif else if
#define bit(x, i) (((x)>>(i))&1)

#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second

#define stoi stoll
#define abs llabs

#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) \
  sort(all(x)), x.erase(unique(all(x)), x.end()), x.shrink_to_fit()

ll popcnt(ll x) { return __builtin_popcountll(x); }
ll popcnt(u64 x) { return __builtin_popcountll(x); }
ll popcnt_mod_2(ll x) { return __builtin_parityll(x); }
ll popcnt_mod_2(u64 x) { return __builtin_parityll(x); }
ll topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
ll topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
ll lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
ll lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T>
T floor(T a, T b) {
  return a / b - (a % b && (a ^ b) < 0);
}
template <typename T>
T ceil(T x, T y) {
  return floor(x + y - 1, y);
}
template <typename T>
T bmod(T x, T y) {
  return x - y * floor(x, y);
}
template <typename T>
pair<T, T> divmod(T x, T y) {
  T q = floor(x, y);
  return {q, x - q * y};
}

template<typename T> T SUM(const vector<T> &A) {
  T s = 0; for (auto &&a: A) s += a;
  return s;
}

template <typename T>
T POP(queue<T> &que) {
  T a = que.front();
  que.pop();
  return a;
}
template <typename T>
T POP(deque<T> &que) {
  T a = que.front();
  que.pop_front();
  return a;
}
template <typename T>
T POP(pq<T> &que) {
  T a = que.top();
  que.pop();
  return a;
}
template <typename T>
T POP(pqg<T> &que) {
  T a = que.top();
  que.pop();
  return a;
}
template <typename T>
T POP(vc<T> &que) {
  T a = que.back();
  que.pop_back();
  return a;
}

template <typename F>
ll binary_search(F check, ll ok, ll ng, bool check_ok = true) {
  if (check_ok) assert(check(ok));
  while (abs(ok - ng) > 1) {
    auto x = (ng + ok) / 2;
    (check(x) ? ok : ng) = x;
  }
  return ok;
}
template <typename F>
f128 binary_search_real(F check, f128 ok, f128 ng, ll iter = 100) {
  rep(iter) {
    f128 x = (ok + ng) / 2;
    (check(x) ? ok : ng) = x;
  }
  return (ok + ng) / 2;
}

// ? は -1
vc<int> s_to_vi(const string &S, char first_char) {
  vc<int> A(S.size());
  rep(i, S.size()) { A[i] = (S[i] != '?' ? S[i] - first_char : -1); }
  return A;
}

template <typename T, typename U>
vc<T> cumsum(vc<U> &A, ll off = 1) {
  ll N = A.size();
  vc<T> B(N + 1);
  rep(i, N) { B[i + 1] = B[i] + A[i]; }
  if (off == 0) B.erase(B.begin());
  return B;
}

// stable sort
template <typename T>
vi argsort(const vector<T> &A) {
  vi ids(len(A));
  iota(all(ids), 0);
  sort(all(ids),
       [&](ll i, ll j) { return (A[i] == A[j] ? i < j : A[i] < A[j]); });
  return ids;
}

// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vi &I) {
  vc<T> B(len(I));
  rep(i, len(I)) B[i] = A[I[i]];
  return B;
}

template<typename T> inline bool chmax(T &a, T b) {return ((a<b)?(a=b,true):(false));}
template<typename T> inline bool chmin(T &a, T b) {return ((a>b)?(a=b,true):(false));}

inline void wt(const char c) { cout << c; }
inline void wt(const string s) { cout << s; }
inline void wt(const char *s) { cout << s; }

template <typename T>
void wt_integer(T x) {
  cout << (x);
}
template <typename T>
void wt_real(T x) {
  cout << fixed << setprecision(15) << (long double)(x);
}
template <typename T>
void wt_integer128(T x) {
  char buf[64];
  char *d = end(buf);
  d--; *d = '\0';
  __uint128_t tmp = ((x < 0)? -x : x);
  do {
    d--; *d = char(tmp%10 + '0'); tmp /= 10;
  } while (tmp);
  if (x < 0) {
    d--; *d = '-';
  }
  cout << d;
}

inline void wt(int x) { wt_integer(x); }
inline void wt(ll x) { wt_integer(x); }
inline void wt(i128 x) { wt_integer128(x); }
inline void wt(u32 x) { wt_integer(x); }
inline void wt(u64 x) { wt_integer(x); }
inline void wt(u128 x) { wt_integer128(x); }
inline void wt(double x) { wt_real(x); }
inline void wt(long double x) { wt_real(x); }
inline void wt(f128 x) { wt_real(x); }

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

void print() { wt('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
  wt(head);
  if (sizeof...(Tail)) wt(' ');
  print(forward<Tail>(tail)...);
}

void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
void onez(bool t = 1) { print(t ? 1 : 0); }
#define endl '\n'
#define dump(x) {cerr << #x " = " << x << '\n';}
#line 2 "main.cpp"

int solve();
int main() {
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  while (!solve()) {}
  return 0;
}

int solve() {
  int n, m, s, a;
  cin >> n >> m;
  if (n == 0 and m == 0) return 1;
  auto hash_state = [&](const vc<stack<int>>& v) -> u64 {
    u64 h = 0;
    for (auto i : v) {
      h *= 31;
      h += i.size();
      while (!i.empty()) {
        h *= 31;
        h += i.top();
        i.pop();
      }
    }
    return h;
  };
  unordered_map<u64, int> memo;
  vc<stack<int>> t(3);
  int nums = 0;
  rep(i, 3) {
    cin >> s;
    nums += s;
    rep(s) {
      cin >> a;
      t[i].push(a);
    }
  }
  rep(i, 0, 3, 2) {
    if (len(t[i]) == nums) {
      print(0);
      return 0;
    }
  }
  queue<pair<vc<stack<int>>, int>> Q;
  memo[hash_state(t)] = 0;
  Q.emplace(mp(t, 0));
  while (!Q.empty()) {
    auto [v, d] = POP(Q);
    if (d >= m) break;
    rep(i, 3) {
      if (v[i].empty()) continue;
      rep(k, -1, 1+1, 2) {
        int j = i + k;
        if (j < 0 || j >= 3) continue;
        if (v[j].empty() or (v[i].top() > v[j].top())) {
          t = v;
          t[j].push(v[i].top());
          if ((j != 1) and (len(t[j]) == nums)) {
            print(d+1);
            return 0;
          }
          t[i].pop();
          u64 h = hash_state(t);
          if (memo.count(h)) continue;
          memo[h] = d+1;
          Q.emplace(mp(t, d+1));
        }
      }
    }
  }
  print(-1);
  return 0;
}
accuracy: 1
time_ms: 2410
memory_kb: 110316
final_rank: 18

code_snippet: #include <queue>
#include <vector>
#include <iostream>


#define INF ((1LL<<62)-(1LL<<31)) /*オーバーフローしない程度に大きい数*/
#define Inf ((1L<<32)-(1L<<10))
#define MOD 1000000007
#define Mod 998244353
#define M_PI 3.14159265358979323846  

using namespace std;

long long solve(long long N, long long M) {
    vector<long long> by;
    by.push_back(1LL);

    for (int i = 1; i < N; i++) {
        by.push_back(by[by.size() - 1] * 3);
    }

    long long n, m, status = 0, maxx = 0;
    for (int i = 0; i < 3; i++) {
        cin >> n;
        for (int j = 0; j < n; j++) {
            cin >> m;
            status += i * by[m - 1];
            maxx += 2 * by[m - 1];
        }
    }

    vector<long long> seen(maxx + 100, INF);
    long long from[4] = { 0,1,1,2 };
    long long to[4] = {1,0,2,1};

    queue<long long> q;
    q.push(status);
    seen[status] = 0;

    long long take;
    while (!q.empty()) {
        take = q.front();
        q.pop();

        vector<long long> s[3];
        for (int i = 0; i < 3; i++) {
            s[i].push_back(-1LL);
        }

        for (int i = 0; i < N; i++) {
            long long tmp = take;
            tmp /= by[i];
            s[tmp % 3].push_back(i);
        }

        for (int i = 0; i < 4; i++) {
            if (s[from[i]].size() > 1 && s[from[i]][s[from[i]].size() - 1] > s[to[i]][s[to[i]].size() - 1]) {
                long long in = take - from[i] * by[s[from[i]][s[from[i]].size() - 1]]
                    + to[i] * by[s[from[i]][s[from[i]].size() - 1]];
                if (seen[in] == INF && seen[take] <= M - 1) {
                    q.push(in);
                    seen[in] = seen[take] + 1;

                    if (in == 0) {
                        return seen[in];
                    }

                    if (in == maxx) {
                        return seen[in];
                    }
                }
            }
        }
    }

    if (min(seen[0], seen[maxx]) != INF) {
        return  min(seen[0], seen[maxx]);
    }
    else {
        return  -1;
    }
}

int main(int argc, char** argv) {
    long long N, M;
    vector<long long> ans;

    cin >> N >> M;
    while (N != 0 || M != 0)
    {
        ans.push_back(solve(N, M));
        cin >> N >> M;
    }

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

    return 0;
}
accuracy: 1
time_ms: 1420
memory_kb: 114844
final_rank: 15

code_snippet: #if !defined(MYLOCAL)//提出時用テンプレート

#pragma GCC optimize("Ofast")
#if defined(NDEBUG)
#undef NDEBUG
#endif
#include "bits/stdc++.h"
#if !defined(_MSC_VER) && __has_include(<atcoder/all>)
#include <atcoder/all>
using namespace atcoder;
#endif
using namespace std;
using     ll=long long;     using   dd=double;     
using    vll=vector<   ll>; using  vdd=vector< dd>;
using   vvll=vector<  vll>; using vvdd=vector<vdd>;
using  vvvll=vector< vvll>; using vvvdd=vector<vvdd>;
using vvvvll=vector<vvvll>;
using   pll=pair<ll,ll>;  using   tll=tuple<ll,ll,ll>; using   qll=tuple<ll,ll,ll,ll>;
using  vpll=vector< pll>; using  vtll=vector< tll>;    using  vqll=vector< qll>;
using vvpll=vector<vpll>; using vvtll=vector<vtll>;    using vvqll=vector<vqll>;
using namespace chrono;
constexpr ll INF = 1001001001001001001;
struct Fast{ Fast(){ cin.tie(0); ios::sync_with_stdio(false); cout<<fixed<<setprecision(numeric_limits<double>::max_digits10); } } fast;
#define REPS(i, S, E) for (ll i = (S); i <= (E); i++)
#define REP(i, N) REPS(i, 0, (N)-1)
#define DEPS(i, S, E) for (ll i = (E); i >= (S); i--)
#define DEP(i, N) DEPS(i, 0, (N)-1)
#define EXPAND( x ) x//VS用おまじない
#define overload3(_1,_2,_3,name,...) name
#define overload4(_1,_2,_3,_4,name,...) name
#define overload5(_1,_2,_3,_4,_5,name,...) name
#define rep3(i, S, E)    for (ll i = (S); i <= (E); i++)
#define rep4(i, S, E, t) for (ll i = (S); i <= (E); i+=(t))
#define rep(...) EXPAND(overload4(__VA_ARGS__,rep4,rep3,_,_)(__VA_ARGS__))
#define dep3(i, E, S)    for (ll i = (E); i >= (S); i--)
#define dep4(i, E, S, t) for (ll i = (E); i >= (S); i-=(t))
#define dep(...) EXPAND(overload4(__VA_ARGS__, dep4, dep3,_,_)(__VA_ARGS__))
#define each2(e,v) for (auto && e:v)
#define each3(a,b,v) for (auto &&[a,b]:v)
#define each4(a,b,c,v) for (auto &&[a,b,c]:v)
#define each5(a,b,c,d,v) for (auto &&[a,b,c,d]:v)
#define each(...) EXPAND(overload5(__VA_ARGS__,each5,each4,each3,each2,_)(__VA_ARGS__))
#define ALL1(v)     (v).begin(),     (v).end()
#define ALL2(v,E)   (v).begin(),     (v).begin()+((E)+1)
#define ALL3(v,S,E) (v).begin()+(S), (v).begin()+((E)+1)
#define ALL(...) EXPAND(overload3(__VA_ARGS__, ALL3, ALL2, ALL1)(__VA_ARGS__))
#define all ALL
#define RALL1(v)     (v).rbegin(),     (v).rend()
#define RALL2(v,E)   (v).rbegin(),     (v).rbegin()+((E)+1)
#define RALL3(v,S,E) (v).rbegin()+(S), (v).rbegin()+((E)+1)
#define RALL(...) EXPAND(overload3(__VA_ARGS__, RALL3, RALL2, RALL1)(__VA_ARGS__))
#define rall RALL
template<class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return true; }return false; }
template<class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return true; }return false; }
template<class T> inline T MaxE(vector<T>&v,ll S,ll E){ T m=v[S]; rep(i,S,E)chmax(m,v[i]); return m; }
template<class T> inline T MinE(vector<T>&v,ll S,ll E){ T m=v[S]; rep(i,S,E)chmin(m,v[i]); return m; }
template<class T> inline T MaxE(vector<T> &v) { return MaxE(v,0,(ll)v.size()-1); }
template<class T> inline T MinE(vector<T> &v) { return MinE(v,0,(ll)v.size()-1); }
template<class T> inline auto maxe(T &&v,ll S,ll E){ return *max_element(ALL(v,S,E)); }
template<class T> inline auto maxe(T &&v){ return *max_element(ALL(v)); }
template<class T> inline auto mine(T &&v,ll S,ll E){ return *min_element(ALL(v,S,E)); }
template<class T> inline auto mine(T &&v){ return *min_element(ALL(v)); }
template<class T> inline T Sum(vector<T> &v,ll S,ll E){ T s=T(); rep(i,S,E)s+=v[i]; return s; }
template<class T> inline T Sum(vector<T> &v) { return Sum(v,0,v.size()-1); }
template<class T,class U=typename remove_reference<T>::type::value_type>
inline U sum(T &&v,ll S,ll E) {return accumulate(all(v,S,E),U());}
template<class T> inline auto sum(T &&v) {return sum(v,0,v.end()-v.begin()-1);}
template<class T> inline ll sz(T &&v){ return (ll)v.size(); }
inline ll CEIL(ll a,ll b){ return (a<0) ? -(-a/b) : (a+b-1)/b; } //負もOK
inline ll FLOOR(ll a,ll b){ return -CEIL(-a,b); } //負もOK

//pair用テンプレート
template<class T,class S> inline pair<T,S>& operator+=(pair<T,S> &a,const pair<T,S> &b){ a.first+=b.first; a.second+=b.second; return a; }
template<class T,class S> inline pair<T,S>& operator-=(pair<T,S> &a,const pair<T,S> &b){ a.first-=b.first; a.second-=b.second; return a; }
template<class T,class S> inline pair<T,S>& operator*=(pair<T,S> &a,const pair<T,S> &b){ a.first*=b.first; a.second*=b.second; return a; }
template<class T,class S> inline pair<T,S>& operator/=(pair<T,S> &a,const pair<T,S> &b){ a.first/=b.first; a.second/=b.second; return a; }
template<class T,class S> inline pair<T,S>& operator%=(pair<T,S> &a,const pair<T,S> &b){ a.first%=b.first; a.second%=b.second; return a; }
template<class T,class S,class R> inline pair<T,S>& operator+=(pair<T,S> &a,R b){ a.first+=b; a.second+=b; return a; }
template<class T,class S,class R> inline pair<T,S>& operator-=(pair<T,S> &a,R b){ a.first-=b; a.second-=b; return a; }
template<class T,class S,class R> inline pair<T,S>& operator*=(pair<T,S> &a,R b){ a.first*=b; a.second*=b; return a; }
template<class T,class S,class R> inline pair<T,S>& operator/=(pair<T,S> &a,R b){ a.first/=b; a.second/=b; return a; }
template<class T,class S,class R> inline pair<T,S>& operator%=(pair<T,S> &a,R b){ a.first%=b; a.second%=b; return a; }
template<class T,class S,class R> inline pair<T,S> operator+(const pair<T,S> &a,R b){ pair<T,S> c=a; return c+=b; }
template<class T,class S,class R> inline pair<T,S> operator-(const pair<T,S> &a,R b){ pair<T,S> c=a; return c-=b; }
template<class T,class S,class R> inline pair<T,S> operator*(const pair<T,S> &a,R b){ pair<T,S> c=a; return c*=b; }
template<class T,class S,class R> inline pair<T,S> operator/(const pair<T,S> &a,R b){ pair<T,S> c=a; return c/=b; }
template<class T,class S,class R> inline pair<T,S> operator%(const pair<T,S> &a,R b){ pair<T,S> c=a; return c%=b; }
template<class T,class S,class R> inline pair<T,S> operator-(R b,const pair<T,S> &a){ pair<T,S> c=-a; return c+=b; }
template<class T,class S> inline pair<T,S> operator-(const pair<T,S> &a,const pair<T,S> &b){ pair<T,S> c=a; return c-=b; }
template<class T,class S> inline pair<T,S> operator-(const pair<T,S> &a){ pair<T,S> c=a; return c*=(-1); }
template<class T,class S> inline ostream &operator<<(ostream &os,const pair<T,S> &a){ return os << a.first << ' ' << a.second; }

//tuple用テンプレート 出力用のみ
template<class T,class S,class R> inline ostream &operator<<(ostream &os,const tuple<T,S,R> &a){ return os << get<0>(a) << ' ' << get<1>(a) << ' ' << get<2>(a); }
template<class T,class S,class R,class Q> inline ostream &operator<<(ostream &os,const tuple<T,S,R,Q> &a){ return os << get<0>(a) << ' ' << get<1>(a) << ' ' << get<2>(a) << ' ' << get<3>(a); }

//vector用テンプレート
template<class T> inline ostream &operator<<(ostream &os,const vector<T> &a){ for (ll i=0; i<(ll)a.size(); i++) os<<(i>0?" ":"")<<a[i];  return os; }

//array用テンプレート
template<class T,size_t S> inline array<T,S>& operator+=(array<T,S> &a,const array<T,S> &b){ for (ll i=0; i<(ll)S; i++) a[i]+=b[i];  return a; }
template<class T,size_t S> inline array<T,S>& operator-=(array<T,S> &a,const array<T,S> &b){ for (ll i=0; i<(ll)S; i++) a[i]-=b[i];  return a; }
template<class T,size_t S> inline array<T,S>& operator*=(array<T,S> &a,const array<T,S> &b){ for (ll i=0; i<(ll)S; i++) a[i]*=b[i];  return a; }
template<class T,size_t S> inline array<T,S>& operator/=(array<T,S> &a,const array<T,S> &b){ for (ll i=0; i<(ll)S; i++) a[i]/=b[i];  return a; }
template<class T,size_t S> inline array<T,S>& operator%=(array<T,S> &a,const array<T,S> &b){ for (ll i=0; i<(ll)S; i++) a[i]%=b[i];  return a; }
template<class T,size_t S,class R> inline array<T,S>& operator+=(array<T,S> &a,R b){ for (T &e: a) e+=b;  return a; }
template<class T,size_t S,class R> inline array<T,S>& operator-=(array<T,S> &a,R b){ for (T &e: a) e-=b;  return a; }
template<class T,size_t S,class R> inline array<T,S>& operator*=(array<T,S> &a,R b){ for (T &e: a) e*=b;  return a; }
template<class T,size_t S,class R> inline array<T,S>& operator/=(array<T,S> &a,R b){ for (T &e: a) e/=b;  return a; }
template<class T,size_t S,class R> inline array<T,S>& operator%=(array<T,S> &a,R b){ for (T &e: a) e%=b;  return a; }
template<class T,size_t S,class R> inline array<T,S> operator+(const array<T,S> &a,R b){ array<T,S> c=a; return c+=b; }
template<class T,size_t S,class R> inline array<T,S> operator-(const array<T,S> &a,R b){ array<T,S> c=a; return c-=b; }
template<class T,size_t S,class R> inline array<T,S> operator*(const array<T,S> &a,R b){ array<T,S> c=a; return c*=b; }
template<class T,size_t S,class R> inline array<T,S> operator/(const array<T,S> &a,R b){ array<T,S> c=a; return c/=b; }
template<class T,size_t S,class R> inline array<T,S> operator%(const array<T,S> &a,R b){ array<T,S> c=a; return c%=b; }
template<class T,size_t S,class R> inline array<T,S> operator-(R b,const array<T,S> &a){ array<T,S> c=-a; return c+=b; }
template<class T,size_t S> inline array<T,S> operator-(const array<T,S> &a,const array<T,S> &b){ array<T,S> c=a; return c-=b; }
template<class T,size_t S> inline array<T,S> operator-(const array<T,S> &a){ array<T,S> c=a; return c*=(-1); }
template<class T,size_t S> inline ostream &operator<<(ostream &os,const array<T,S> &a){ for (ll i=0; i<(ll)S; i++) os<<(i>0?" ":"")<<a[i];  return os; }


#endif//テンプレートend

#if defined(_MSC_VER) && __has_include(<atcoder/all>)
#include <atcoder/all>
using namespace atcoder;
#endif
struct{
	system_clock::time_point st = system_clock::now();
	ll operator()()const{return duration_cast<microseconds>(system_clock::now()-st).count()/1000;}
} timeget;
//////////////////////////////////////////


template<long long MOD> struct mll_{
	using Int = long long;
	using ll = long long;
	ll val_=0;
	/*---- utility ----*/
	mll_ &norm(){ return normR().normS(); }//正規化
	mll_ &normR(){ val_%=MOD; return *this; }//剰余正規化のみ
	mll_ &normS(){ if (val_<0) val_+=MOD; return *this; }//正負正規化のみ
	mll_ &normP(){ if (val_>=MOD) val_-=MOD; return *this; }//加算時正規化
	mll_ &invsg(){ val_=-val_; return normS(); }//正負反転
	ll modinv(int a){//a^-1 mod MOD
		int ypre=0,y=1,apre=MOD;
		while (a>1){
			int t=apre/a;
			apre-=a*t,swap(a,apre);
			ypre-=y*t,swap(y,ypre);
		}
		return y<0 ? y+MOD: y;
	}
	/*---- I/F ----*/
	mll_(){}
	mll_(ll v): val_(v){ norm(); }
	mll_(ll v,bool b): val_(v){} //正規化無のコンストラクタ
	Int val()const{ return (Int)val_; }
	bool isnone() const { return val_==-1; } //true:値なし
	mll_ &none() { val_=-1; return *this; } //値なしにする
	mll_ &inv(){ val_=modinv((int)val_); return *this; }
	mll_ &operator+=(mll_ b){ val_+=b.val_; return normP(); }
	mll_ &operator-=(mll_ b){ val_-=b.val_; return normS(); }
	mll_ &operator*=(mll_ b){ val_*=b.val_; return normR(); }
	mll_ &operator/=(mll_ b){ return *this*=b.inv(); }
	mll_ &operator+=(ll b){ return *this+=mll_(b); }
	mll_ &operator-=(ll b){ return *this-=mll_(b); }
	mll_ &operator*=(ll b){ return *this*=mll_(b); }
	mll_ &operator/=(ll b){ return *this/=mll_(b); }
	mll_ operator-()const{ return mll_(*this).invsg(); }
	mll_ operator+(mll_ b)const{ return mll_(*this)+=b; }
	mll_ operator-(mll_ b)const{ return mll_(*this)-=b; }
	mll_ operator*(mll_ b)const{ return mll_(*this)*=b; }
	mll_ operator/(mll_ b)const{ return mll_(*this)/=b; }
	mll_ operator+(ll b)const{ return mll_(*this)+=b; }
	mll_ operator-(ll b)const{ return mll_(*this)-=b; }
	mll_ operator*(ll b)const{ return mll_(*this)*=b; }
	mll_ operator/(ll b)const{ return mll_(*this)/=b; }
	friend mll_ operator+(ll a,mll_ b){ return b+a; }
	friend mll_ operator-(ll a,mll_ b){ return -b+a; }
	friend mll_ operator*(ll a,mll_ b){ return b*a; }
	friend mll_ operator/(ll a,mll_ b){ return mll_(a)/b; }
	bool operator==(mll_ b)const{ return val_==b.val_; }
	bool operator!=(mll_ b)const{ return val_!=b.val_; }
	bool operator==(ll b)const{ return *this==mll_(b); }
	bool operator!=(ll b)const{ return *this!=mll_(b); }
	friend bool operator==(ll a,mll_ b){ return mll_(a)==b; }
	friend bool operator!=(ll a,mll_ b){ return mll_(a)!=b; }
	friend ostream &operator<<(ostream &os,mll_  a){ return os << a.val_; }
	friend istream &operator>>(istream &is,mll_ &a){ return is >> a.val_; }
	mll_ pow(ll k)const{
		mll_ ret(1,false),a(*this);
		for (; k>0; k>>=1,a*=a) if (k&1)ret*=a;
		return ret;
	}
	static constexpr int mod() { return MOD; }
	//enum{ modll=MOD };
};
#if 0
#define MODLL (1000000007LL)
#else
#define MODLL (998244353LL)
#endif
using mll = mll_<MODLL>;
//using mll = fraction;
using vmll    = std::vector<mll>;
using vvmll   = std::vector<vmll>;
using vvvmll  = std::vector<vvmll>;
using vvvvmll = std::vector<vvvmll>;


template<class T> struct Vector: vector<T>{
	using Int = long long;
	using vT=vector<T>;
	using cvT=const vector<T>;
	using cT=const T;
	using vT::vT; //親クラスのコンストラクタの隠蔽を回避
	using vT::begin,vT::end,vT::insert,vT::erase;
	auto it(Int i){ return begin()+i; }
	auto it(Int i)const{ return begin()+i; }
	Vector(cvT& b):vT(b){}
	Vector(vT&& b):vT(move(b)){}
	Vector(Int n,T s,T d){ iota(n,s,d); }
	template<class S> Vector &operator+=(S x){ for (T &e: *this) e+=x;  return *this; }
	template<class S> Vector &operator-=(S x){ for (T &e: *this) e-=x;  return *this; }
	template<class S> Vector &operator*=(S x){ for (T &e: *this) e*=x;  return *this; }
	template<class S> Vector &operator/=(S x){ for (T &e: *this) e/=x;  return *this; }
	template<class S> Vector &operator%=(S x){ for (T &e: *this) e%=x;  return *this; }
	template<class S> Vector operator+(S x)const{ return Vector(*this)+=x; }
	template<class S> Vector operator-(S x)const{ return Vector(*this)-=x; }
	template<class S> Vector operator*(S x)const{ return Vector(*this)*=x; }
	template<class S> Vector operator/(S x)const{ return Vector(*this)/=x; }
	template<class S> Vector operator%(S x)const{ return Vector(*this)%=x; }
	Vector operator-()const{ return Vector(*this)*=-1; }
	template<class S> friend Vector operator-(S x,const Vector &a){ return -a+=x; }
	Int size()const{ return (Int)vT::size(); }
	Vector &push_back(cT& x){ vT::push_back(x); return *this; }
	Vector &pop_back(){ vT::pop_back(); return *this; }
	Vector &push_front(cT& x){ insert(begin(),x); return *this; }
	Vector &pop_front(){ erase(0); return *this; }
	Vector &insert(Int i,cT& x){ insert(it(i),x); return *this; }
	Vector &insert(Int i,cvT& b){ insert(it(i),b.begin(),b.end()); return *this; }
	Vector &erase(Int i){ erase(it(i)); return *this; }
	Vector &erase(Int l,Int r){ erase(it(l),it(r+1)); return *this; }
	Vector &concat(cvT &b){ insert(end(),b.begin(),b.end()); return *this; }
	Vector &concat(cvT &b,Int n){ for (int i=0;i<n;++i) concat(b); return *this; }
	Vector &repeat(Int n){ concat(vT(*this),n-1); return *this; }
	Vector &reverse(){ std::reverse(begin(),end()); return *this; }
	Vector &sort(){ std::sort(begin(),end()); return *this; }
	Vector &rsort(){ std::sort(vT::rbegin(),vT::rend()); return *this; }
	template<class Pr> Vector &sort(Pr pr){ std::sort(begin(),end(),pr); return *this; }
	Vector &uniq(){ erase(unique(begin(),end()),end()); return *this; }
	Vector &sortq(){ return sort().uniq(); }
	Vector &fill(Int l,Int r,cT& x){ std::fill(it(l),it(r+1),x); return *this; }
	template<class S=Int> Vector &iota(Int n,T s=0,S d=1){
		vT::resize(n);
		if (n==0) return *this;
		(*this)[0]=s;
		for (int i=1;i<n;++i) (*this)[i]=(*this)[i-1]+d;
		return *this;
	}
	Int count(cT& x)const{ return Int(std::count(begin(),end(),x)); }
	Int count(Int l,Int r,cT& x)const{ return Int(std::count(it(l),it(r+1),x)); }
	template<class Pr> Int countif(Pr pr)const{ return Int(count_if(begin(),end(),pr)); }
	template<class Pr> Int countif(Int l,Int r,Pr pr)const{ return Int(count_if(it(l),it(r+1),pr)); }
	Int find(cT& x)const{ return Int(std::find(begin(),end(),x)-begin()); }
	Int find(Int l,Int r,cT& x)const{ return Int(std::find(it(l),it(r+1),x)-begin()); }
	template<class Pr> Int findif(Pr pr)const{ return Int(find_if(begin(),end(),pr)-begin()); }
	template<class Pr> Int findif(Int l,Int r,Pr pr)const{ return Int(find_if(it(l),it(r+1),pr)-begin()); }
	Vector<Int> findall(cT& x)const{ return findall(0,size()-1,x); }
	Vector<Int> findall(Int l,Int r,cT& x)const{ return findallif(l,r,[&](cT& y){return y==x;}); }
	template<class Pr> Vector<Int> findallif(Pr pr)const{ return findallif(0,size()-1,pr); }
	template<class Pr> Vector<Int> findallif(Int l,Int r,Pr pr)const{
		Vector<Int> ret;
		for (Int i=l;i<=r;++i) if (pr((*this)[i])) ret.push_back(i);
		return ret;
	}
	Int  flooridx(cT& x)const{ return Int(upper_bound(begin(),end(),x)-begin()-1); }
	Int   ceilidx(cT& x)const{ return Int(lower_bound(begin(),end(),x)-begin()); }
	Int  leftnmof(cT& x)const{ return flooridx(x)+1; }
	Int rightnmof(cT& x)const{ return size()-ceilidx(x); }
	bool contains(cT& x)const{ Int i=flooridx(x); return i>=0 && (*this)[i]==x; }
	template<class Pr> Int  flooridx(cT& x,Pr pr)const{ return Int(upper_bound(begin(),end(),x,pr)-begin()-1); }
	template<class Pr> Int   ceilidx(cT& x,Pr pr)const{ return Int(lower_bound(begin(),end(),x,pr)-begin()); }
	template<class Pr> Int  leftnmof(cT& x,Pr pr)const{ return flooridx(x,pr)+1; }
	template<class Pr> Int rightnmof(cT& x,Pr pr)const{ return size()-ceilidx(x,pr); }
	template<class Pr> bool contains(cT& x,Pr pr)const{ Int i=flooridx(x,pr); return i>=0 && (*this)[i]==x; }
};
/*
vll a={9,8,7},b={1,2,3};
vpll p={{5,3},{7,8},{0,2},};
- -------- 操作系 --------
a+=x a-=x a*=x a/=x a%=x a+x a-x a*x a/x a%x -a x-a  //∀i a[i]にxを演算
a.push_front(x);
a.push_back(x);
a.pop_front();
a.pop_back();
a.insert(i,x); //a[i]にx挿入
a.insert(i,b); //a[i]にvll b挿入
a.erase(i);    //a[i]削除
a.erase(l,r);  //区間[l,r]削除
a.concat(b);   //aにbを結合
a.concat(b,n); //aにbをn回結合
a.repeat(n);   //aをn回繰り返す
a.reverse(); //反転
a.sort();    //ソート
a.rsort();   //逆順ソート
p.sort([&](pll x,pll y){return x.second<y.second;});//比較関数指定ソート
a.uniq();      //連続同値を1つにする
a.sortq();     //ソートしてユニーク
a.fill(l,r,x); //[l,r]にx代入
a.iota(n,s,d); //aを等差数列にする 長さn,初項s,公差d
vll a(n,s,d);  //コンストラクタ版iota
- -------- 検索系 --------
auto pr=[&](auto &x){ return x>0; };  //検索条件
ll m=a.count(x);     //xの個数
ll m=a.count(l,r,x); //xの個数in[l,r]
ll m=a.countif(pr);     //条件満たす個数
ll m=a.countif(l,r,pr); //条件満たす個数in[l,r]
ll i=a.find(x);         //xの最左位置i         ない時N(配列長)
ll i=a.find(l,r,x);     //xの最左位置i in[l,r] ない時r+1
ll i=a.findif(pr);      //条件満たす最左位置i         ない時N(配列長)
ll i=a.findif(l,r,pr);  //条件満たす最左位置i in[l,r] ない時r+1
vll is=a.findall(x);        //xの位置i列挙
vll is=a.findall(l,r,x);    //xの位置i列挙in[l,r]
vll is=a.findallif(pr);     //条件満たす位置i列挙
vll is=a.findallif(l,r,pr); //条件満たす位置i列挙in[l,r]
- -------- 昇順sort済み配列用 --------
ll i=a.flooridx(x);   //x以下の最近傍位置i ない時-1
ll i=a.ceilidx(x);    //x以上の最近傍位置i ない時N(配列長)
ll m=a.leftnmof(x);   //x以下の個数
ll m=a.rightnmof(x);  //x以上の個数
bool b=a.contains(x); //xを含む
- -------- 比較関数prでsort済みの配列用 --------
auto pr=[&](auto &x,auto &y){ return x>y; }; //降順ソート時
ll i=a.flooridx(x,pr);   //x以左の最近傍位置i ない時-1
ll i=a.ceilidx(x,pr);    //x以右の最近傍位置i ない時N(配列長)
ll m=a.leftnmof(x,pr);   //x以左の個数
ll m=a.rightnmof(x,pr);  //x以右の個数
bool b=a.contains(x,pr); //xを含む

a.concat(b,n).pop_back().rsort().uniq();  //連続適用できる
*/

namespace SolvingSpace{

template<class T> using vector = Vector<T>;
using    vll=vector<   ll>; using    vmll=vector<   mll>; using   vdd=vector<  dd>;
using   vvll=vector<  vll>; using   vvmll=vector<  vmll>; using  vvdd=vector< vdd>;
using  vvvll=vector< vvll>; using  vvvmll=vector< vvmll>; using vvvdd=vector<vvdd>;
using vvvvll=vector<vvvll>; using vvvvmll=vector<vvvmll>;
using   vpll=vector<  pll>; using    vtll=vector<   tll>; using  vqll=vector< qll>;
using  vvpll=vector< vpll>; using   vvtll=vector<  vtll>; using vvqll=vector<vqll>;

template<class DATA,class Tran,class Toid> struct BFSCalc{
	using Int = long long;
	using ll = int;
	Tran tran; //DATA dを遷移させるラムダ式
	Toid toid; //DATA dをシリアライズするラムダ式
	ll Inf;
	vector<ll> dist;
	deque<DATA> dq;
	BFSCalc(DATA,Tran tran_,Toid toid_,ll Inf_): tran(tran_),toid(toid_),Inf(Inf_){}
	ll calc(const DATA &s){ return calcMul(vector<DATA>{s,}); }
	ll calcMul(const vector<DATA> &ss){ //BFS処理本体
		for (const DATA &s: ss) (*this)[s]=0, dq.push_back(s); //初期値セット
		while (dq.size()){
			DATA d=dq.front();  dq.pop_front();
			if (
				d.sts[1].size()==0 and (d.sts[0].size()==0 or d.sts[2].size()==0)
				) return (*this)[d]; //ゴールで停止し距離を返す時
			for (const DATA &nd: tran(d)){
				if (ChMin((*this)[nd],(*this)[d]+1)) dq.push_back(nd);
			}
		}
		return Inf;
	}
	ll &operator[](const DATA &d){
		ll dataid=toid(d);
		if ((ll)dist.size()<=dataid) dist.resize(dataid+1,Inf);
		return dist[dataid];
	}
	vector<ll> tovll(){ return dist; }
	vector<ll> tovll(ll sx,ll ex){ dist.resize(ex-sx+1,Inf); return dist; }
	vector<vector<ll>> tovvll(ll sx,ll ex,ll sy,ll ey){
		ll H=ex-sx+1,W=ey-sy+1;
		vector<vector<ll>> ret(H,vector<ll>(W));
		dist.resize(H*W,Inf);
		for (ll i=0;i<H;++i) for (ll j=0;j<W;++j) ret[i][j]=dist[i*W+j];
		return ret;
	}
private:
	template<class T> bool ChMin(T &a,T b){ bool r=a>b; if(r)a=b; return r; }
};
/*
- -------- 定義 --------
struct DATA{ ll x,y; };
auto trans=[&](const DATA &d){
	vector<DATA> ret; //ここに遷移後データ達を入れる
	for (auto&&[dx,dy]:dxy){
		if (!isout(d.x+dx,d.y+dy)) ret.push_back({d.x+dx,d.y+dy});
	}
	return ret;
};
auto toid=[&](const DATA &d){ return d.x*W+d.y; };
BFSCalc dist(DATA(),trans,toid,INF);
.                              ↑∞の値
- -------- 計算 --------
.                 ↓初期状態
dist.calc({sx,sy,sxx,syy});
.             ↓vector<DATA> 初期状態複数指定
dist.calcMul(ss);
- -------- 結果取得 --------
ll d=dist[{0,1,2,4}];
vll  ds=dist.tovll (-1,n-1);
vvll ds=dist.tovvll(0,H-1,0,W-1);
*/


template<class T> vector<T> powers(T m,ll n){
	vector<T> ret(n+1,1);
	for (ll i=1;i<=n;++i) ret[i]=ret[i-1]*m;
	return ret;
}
/*
.    ↓two[i]=2^i  2^0～2^nを準備
vmll two=powers(mll(2),n);
*/

void cin2solve()
{
	using vcc=vector<char>;
	using vvcc=vector<vector<char>>;
	while (true){
		ll n,m;
		cin >> n >> m;
		if (n==0 and m==0)break;

		vvcc sts(3);
		rep(t,0,3-1){
			ll nm; cin >> nm;
			rep(times,0,nm-1){
				ll x; cin >> x;
				sts[t].push_back(char(x));
			}
		}

		struct DATA{ vvcc sts; };
		auto trans=[&](const DATA &d){
			DATA e=d;
			vector<DATA> ret; //ここに遷移後データ達を入れる
			auto isok=[&](vcc &a,vcc &b){//true:a→bへ移動可能
				if (a.empty()) return false;
				if (b.empty()) return true;
				return a.back()>b.back();
			};
			auto move=[&](vcc &a,vcc &b){//a→bへ移動
				b.push_back(a.back());
				a.pop_back();
			};
			auto func=[&](ll i,ll j){
				if (isok(e.sts[i],e.sts[j])){
					move(e.sts[i],e.sts[j]);
					ret.push_back(e);
					move(e.sts[j],e.sts[i]);
				}
			};
			func(0,1);
			func(1,0);
			func(1,2);
			func(2,1);
			return ret;
		};
		map<vvcc,ll> mp;
		auto toidmap=[&](const DATA &d){
			if (mp.count(d.sts)==1) return mp[d.sts];
			ll no=sz(mp);
			return mp[d.sts]=no;
		};

		vll three=powers(3ll,15);
		auto toid=[&](const DATA &d){
			ll id=0;
			rep(va,0,3-1){
				for (auto&& e: d.sts[va]) id+=three[e-1]*va;
			}
			return id;
		};

		BFSCalc dist(DATA(),trans,toid,1000000010);

		ll ans=dist.calc({sts,});
		if (ans>m) ans=-1;
		cout << ans << '\n';
	}


	return;
}

};//SolvingSpace

//////////////////////////////////////////

int main(){
#if 1
	//SolvingSpace::labo();
	SolvingSpace::cin2solve();
	//SolvingSpace::generand();
#else
	ll t;  cin >> t;
	rep(i,0,t-1){
		SolvingSpace::cin2solve();
		//SolvingSpace::generand();
	} 
#endif
	//cerr << timeget() <<"ms"<< '\n';
	return 0;
}
accuracy: 1
time_ms: 1190
memory_kb: 114232
final_rank: 14