Problem:
Problem F:
Gap
Let’s play a card game called Gap.
You have 28 cards labeled with two-digit numbers. The first digit (from 1 to 4) represents the
suit of the card, and the second digit (from 1 to 7) represents the value of the card.
First, you shuffle the cards and lay them face up on the table in four rows of seven cards, leaving
a space of one card at the extreme left of each row. The following shows an example of initial
layout.
Next, you remove all cards of value 1, and put them in the open space at the left end of the
rows: “11” to the top row, “21” to the next, and so on.
Now you have 28 cards and four spaces, called gaps, in four rows and eight columns. You start
moving cards from this layout.
At each move, you choose one of the four gaps and fill it with the successor of the left neighbor
of the gap. The successor of a card is the next card in the same suit, when it exists. For instance
the successor of “42” is “43”, and “27” has no successor.
In the above layout, you can move “43” to the gap at the right of “42”, or “36” to the gap at
the right of “35”. If you move “43”, a new gap is generated to the right of “16”. You cannot
move any card to the right of a card of value 7, nor to the right of a gap.
The goal of the game is, by choosing clever moves, to make four ascending sequences of the same
suit, as follows.
Your task is to find the minimum number of moves to reach the goal layout.
Input
The input starts with a line containing the number of initial layouts that follow.
Each layout consists of five lines - a blank line and four lines which represent initial layouts of
four rows. Each row has seven two-digit numbers which correspond to the cards.
Output
For each initial layout, produce a line with the minimum number of moves to reach the goal
layout. Note that this number should not include the initial four moves of the cards of value 1.
If there is no move sequence from the initial layout to the goal layout, produce “-1”.
Sample Input
4

12 13 14 15 16 17 21
22 23 24 25 26 27 31
32 33 34 35 36 37 41
42 43 44 45 46 47 11

26 31 13 44 21 24 42
17 45 23 25 41 36 11
46 34 14 12 37 32 47
16 43 27 35 22 33 15

17 12 16 13 15 14 11
27 22 26 23 25 24 21
37 32 36 33 35 34 31
47 42 46 43 45 44 41

27 14 22 35 32 46 33
13 17 36 24 44 21 15
43 16 45 47 23 11 26
25 37 41 34 42 12 31
Output for the Sample Input
0
33
60
-1

Submitted solutions:

code_snippet: #include <iostream>
#include <cstring>
#include <climits>
#include <queue>
#include <unordered_set>
 
using namespace std;
 
class State
{
public:
    /**
     * 表格数字
     */
    int table[4][8];
    /**
     * 移动回数
     */
    int turn;
 
 
    State(int card[4][7])
    {
        for (int i = 0; i < 4; i++)
            table[i][0] = (10 * (i + 1) + 1);// 11 21 31 41
        for (int i = 0; i < 4; i++)
        {
            memcpy(table[i] + 1, card[i], 7 * sizeof(int));
        }
        // 从这种布局开始游戏
        for (int i = 0; i < 4; i++)
        {
            for (int j = 1; j < 8; j++)
            {
                if (table[i][j] == 11 || table[i][j] == 21 || table[i][j] == 31 || table[i][j] == 41)
                    table[i][j] = 0;
            }
        }
        turn = 0;
    }
 
    State(const State &t)
    {
        memcpy(table, t.table, sizeof(table));
        turn = t.turn;
    }
 
    /**
     * 可以填充空白
     * @param x
     * @param y
     * @return
     */
    bool can_fill_gap(int x, int y)
    {
        if (table[x][y] != 0)
            return false;
        else if (table[x][y - 1] == 0 || (table[x][y - 1]) % 10 == 7) // x7 has no successor
            return false;
        else
            return true;
    }
 
    /**
     * 填充空白
     * @param x
     * @param y
     */
    void fill_gap(int x, int y)
    {
        int s, sx, sy;
        sx = sy = -1;
 
        s = table[x][y - 1] + 1;
 
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                if (table[i][j] == s)
                {
                    sx = i;
                    sy = j;
                }
            }
        }
 
        table[x][y] = table[sx][sy];
        table[sx][sy] = 0;
 
        turn++;
    }
 
    /**
     * 是否是游戏结束状态，即每行都是升序，最后一列全为0
     * @return
     */
    bool done()
    {
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 7; j++)
            {
                if (table[i][j] != (10 * (i + 1) + (j + 1)))
                    return false;
            }
            if (table[i][7] != 0)
                return false;
        }
 
        return true;
    }
 
    bool operator==(const State &s) const
    {
        int i, j;
        for (i = 0; i < 4; i++)
        {
            for (j = 1; j < 8; j++)
            {
                if (table[i][j] != s.table[i][j])
                    return false;
            }
        }
        return true;
    }
 
};
 
struct StateHash
{
    size_t operator()(const State &s) const
    {
        size_t hash = 0;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 1; j < 8; j++)
            {
                hash += s.table[i][j];
                hash <<= 1;
            }
        }
 
        return hash;
    }
};
 
int solve(int card[4][7])
{
    queue<State> que;
    unordered_set<State, StateHash> visited;
    //准备BFS
    bool end = false;
    int ans = INT_MAX;
    State init(card);
    if (init.done())
        return 0;
    que.push(init);
    visited.insert(init);
    //BFS
    while (!que.empty() && !end)
    {
        State s = que.front();
        que.pop();
        for (int i = 0; i < 4; i++)
        {
            for (int j = 1; j < 8; j++)
            {
                if (s.can_fill_gap(i, j))
                {
                    State temp(s);
                    temp.fill_gap(i, j);
                    // 结束
                    if (temp.done())
                    {
                        end = true;
                        ans = temp.turn;
                    }// 未遍历
                    else if (visited.find(temp) == visited.end())
                    {
                        que.push(temp);
                        visited.insert(temp);
                    }
                }
            }
        }
    }
 
    if (ans == INT_MAX)
        ans = -1;
    return ans;
}
 
int main()
{
    int n;
    scanf("%d", &n);
    while (n--)
    {
        int card[4][7];
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 7; ++j)
            {
                scanf("%d", &card[i][j]);
            }
        }
 
        printf("%d\n", solve(card));
    }
    return 0;
}
accuracy: 1
time_ms: 70
memory_kb: 14380
final_rank: 2

code_snippet: //#include<bits/stdc++.h>
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<map>
#include<unordered_set>
using namespace std;
#define inf 0x3f3f3f3f

typedef long long ll;
typedef unsigned long long ULL;
typedef pair<int,int> P;

class State{
public:
    int arr[4][8];
    int times;

    State(int a[][7]){
        times=0;
        arr[0][0]=11;
        arr[1][0]=21;
        arr[2][0]=31;
        arr[3][0]=41;
        for(int i=0;i<4;i++){
            memcpy(arr[i]+1,a[i],sizeof(int)*7);
        }
        for(int i=0;i<4;i++){
            for(int j=1;j<=7;j++){
                if(arr[i][j]==11||arr[i][j]==21||arr[i][j]==31||arr[i][j]==41){
                    arr[i][j]=0;
                }
            }
        }
    }

    bool operator == (const State& y)const{
        for(int i=0;i<4;i++){
            for(int j=0;j<8;j++){
                if(arr[i][j]!=y.arr[i][j]){
                    return false;
                }
            }
        }
        return true;
    }

    State(const State& y){
        memcpy(arr,y.arr,sizeof(arr));
        times=y.times;
    }

    bool can_fill(int x,int y){
        if(arr[x][y]!=0){
            return false;
        }
        if(arr[x][y-1]==0||arr[x][y-1]%10==7){
            return false;
        }
        return true;
    }

    void fill_gap(int x,int y){
        int tx,ty;
        int target=arr[x][y-1]+1;
        for(int i=0;i<4;i++){
            for(int j=1;j<8;j++){
                if(arr[i][j]==target){
                    tx=i;
                    ty=j;
                    break;
                }
            }
        }
        arr[x][y]=target;
        arr[tx][ty]=0;
        times++;
    }

    bool done(){
        for(int i=0;i<4;i++){
            for(int j=0;j<7;j++){
                if(arr[i][j]!=(i+1)*10+(j+1)){
                    return false;
                }
            }
            if(arr[i][7]!=0){
                return false;
            }
        }
        return true;
    }

};

struct State_Hash{
    size_t operator() (const State &x)const{
        size_t hash=0;
        for(int i=0;i<4;i++){
            for(int j=0;j<8;j++){
                hash+=x.arr[i][j];
                hash<<=1;
            }
        }
        return hash;
    }
};

int bfs(int a[4][7]){
    unordered_set<State,State_Hash> visit;
    State init(a);
    if(init.done()){
        return 0;
    }
    visit.insert(init);
    queue<State> Q;
    Q.push(init);
    while(!Q.empty()){
        State now=Q.front();
        Q.pop();
        for(int i=0;i<4;i++){
            for(int j=1;j<8;j++){
                if(now.can_fill(i,j)){
                    State  newS(now);
                    newS.fill_gap(i,j);
                    if(visit.find(newS)!=visit.end()){
                        continue;
                    }
                    if(newS.done()){
                        return newS.times;
                    }
                    Q.push(newS);
                    visit.insert(newS);
                }
            }
        }
    }
    return -1;
}


int main()
{
    int T;
    scanf("%d",&T);
    while(T--){
        int a[4][7];
        for(int i=0;i<4;i++){
            for(int j=0;j<7;j++){
                scanf("%d",&a[i][j]);
            }
        }
        printf("%d\n",bfs(a));
    }
    return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 15232
final_rank: 4

code_snippet: #include <iostream>
#include <cstring>
#include <climits>
#include <queue>
#include <unordered_set>
 
using namespace std;
 
class State
{
public:
    /**
     * 表格数字
     */
    int table[4][8];
    /**
     * 移动回数
     */
    int turn;
 
 
    State(int card[4][7])
    {
        for (int i = 0; i < 4; i++)
            table[i][0] = (10 * (i + 1) + 1);// 11 21 31 41
        for (int i = 0; i < 4; i++)
        {
            memcpy(table[i] + 1, card[i], 7 * sizeof(int));
        }
        // 从这种布局开始游戏
        for (int i = 0; i < 4; i++)
        {
            for (int j = 1; j < 8; j++)
            {
                if (table[i][j] == 11 || table[i][j] == 21 || table[i][j] == 31 || table[i][j] == 41)
                    table[i][j] = 0;
            }
        }
        turn = 0;
    }
 
    State(const State &t)
    {
        memcpy(table, t.table, sizeof(table));
        turn = t.turn;
    }
 
    /**
     * 可以填充空白
     * @param x
     * @param y
     * @return
     */
    bool can_fill_gap(int x, int y)
    {
        if (table[x][y] != 0)
            return false;
        else if (table[x][y - 1] == 0 || (table[x][y - 1]) % 10 == 7) // x7 has no successor
            return false;
        else
            return true;
    }
 
    /**
     * 填充空白
     * @param x
     * @param y
     */
    void fill_gap(int x, int y)
    {
        int s, sx, sy;
        sx = sy = -1;
 
        s = table[x][y - 1] + 1;
 
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                if (table[i][j] == s)
                {
                    sx = i;
                    sy = j;
                }
            }
        }
 
        table[x][y] = table[sx][sy];
        table[sx][sy] = 0;
 
        turn++;
    }
 
    /**
     * 是否是游戏结束状态，即每行都是升序，最后一列全为0
     * @return
     */
    bool done()
    {
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 7; j++)
            {
                if (table[i][j] != (10 * (i + 1) + (j + 1)))
                    return false;
            }
            if (table[i][7] != 0)
                return false;
        }
 
        return true;
    }
 
    bool operator==(const State &s) const
    {
        int i, j;
        for (i = 0; i < 4; i++)
        {
            for (j = 1; j < 8; j++)
            {
                if (table[i][j] != s.table[i][j])
                    return false;
            }
        }
        return true;
    }
 
};
 
struct StateHash
{
    size_t operator()(const State &s) const
    {
        size_t hash = 0;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 1; j < 8; j++)
            {
                hash += s.table[i][j];
                hash <<= 1;
            }
        }
 
        return hash;
    }
};
 
int solve(int card[4][7])
{
    queue<State> que;
    unordered_set<State, StateHash> visited;
    //准备BFS
    bool end = false;
    int ans = INT_MAX;
    State init(card);
    if (init.done())
        return 0;
    que.push(init);
    visited.insert(init);
    //BFS
    while (!que.empty() && !end)
    {
        State s = que.front();
        que.pop();
        for (int i = 0; i < 4; i++)
        {
            for (int j = 1; j < 8; j++)
            {
                if (s.can_fill_gap(i, j))
                {
                    State temp(s);
                    temp.fill_gap(i, j);
                    // 结束
                    if (temp.done())
                    {
                        end = true;
                        ans = temp.turn;
                    }// 未遍历
                    else if (visited.find(temp) == visited.end())
                    {
                        que.push(temp);
                        visited.insert(temp);
                    }
                }
            }
        }
    }
 
    if (ans == INT_MAX)
        ans = -1;
    return ans;
}
 
int main()
{
    int n;
    scanf("%d", &n);
    while (n--)
    {
        int card[4][7];
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 7; ++j)
            {
                scanf("%d", &card[i][j]);
            }
        }
 
        printf("%d\n", solve(card));
    }
    return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 15196
final_rank: 3

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;

struct Data{
	void set(int arg_row,int arg_col){
		row = arg_row;
		col = arg_col;
	}
	int row,col;
};

struct Info{
	int table[4][8],count;
	Data sace_loc[4];
	Data num_loc[48];
};

map<string,bool> MAP;
int ans_table[4][8];

string makeString(int table[4][8]){

	string ret;
	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			ret.append(to_string(table[row][col]));
		}
	}
	return ret;
}

bool checkClear(int table[4][8]){

	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			if(table[row][col] != ans_table[row][col])return false;
		}
	}

	return true;
}

void copyInfo(Info& to,Info from){

	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			to.table[row][col] = from.table[row][col];
		}
	}

	for(int i = 0; i < 4; i++){
		to.sace_loc[i] = from.sace_loc[i];
	}

	for(int i = 0; i < 48; i++)to.num_loc[i] = from.num_loc[i];
}


void func(){
	MAP.clear();

	Info first;
	first.table[0][0] = 0;
	first.table[1][0] = 0;
	first.table[2][0] = 0;
	first.table[3][0] = 0;

	for(int row = 0; row < 4; row++){
		for(int col = 1; col <= 7; col++){
			scanf("%d",&first.table[row][col]);
			switch(first.table[row][col]){
			case 11:
				first.table[0][0] = 11;
				first.table[row][col] = 0;
				first.sace_loc[0].set(row,col);
				break;
			case 21:
				first.table[1][0] = 21;
				first.table[row][col] = 0;
				first.sace_loc[1].set(row,col);
				break;
			case 31:
				first.table[2][0] = 31;
				first.table[row][col] = 0;
				first.sace_loc[2].set(row,col);
				break;
			case 41:
				first.table[3][0] = 41;
				first.table[row][col] = 0;
				first.sace_loc[3].set(row,col);
				break;
			default:
				first.num_loc[first.table[row][col]].set(row,col);
				break;
			}
		}
	}

	first.count = 0;
	string tmp = makeString(first.table);
	MAP[tmp] = true;

	queue<Info> Q;
	Q.push(first);

	int left_num;

	Data tmp_data;

	while(!Q.empty()){

		if(checkClear(Q.front().table)){
			printf("%d\n",Q.front().count);
			return;
		}else{

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

				left_num = Q.front().table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col-1];

				if(left_num == 0 || left_num%10 == 7)continue;

				tmp_data = Q.front().num_loc[left_num+1];

				Info next_info;
				copyInfo(next_info,Q.front());
				next_info.table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col] = left_num+1;
				next_info.table[tmp_data.row][tmp_data.col] = 0;
				next_info.num_loc[left_num+1].set(Q.front().sace_loc[i].row,Q.front().sace_loc[i].col);

				tmp = makeString(next_info.table);

				auto at = MAP.find(tmp);
				if(at != MAP.end())continue;

				MAP[tmp] = true;
				next_info.sace_loc[i].set(tmp_data.row,tmp_data.col);
				next_info.count = Q.front().count+1;
				Q.push(next_info);
			}
			Q.pop();
		}
	}

	printf("-1\n");
}

int main(){

	for(int col = 0; col <= 6; col++)ans_table[0][col] = 11+col;
	ans_table[0][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[1][col] = 21+col;
	ans_table[1][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[2][col] = 31+col;
	ans_table[2][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[3][col] = 41+col;
	ans_table[3][7] = 0;

	int case_num;
	scanf("%d",&case_num);

	for(int i = 0; i < case_num; i++)func();

}
accuracy: 1
time_ms: 2390
memory_kb: 14780
final_rank: 12

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;

struct Data{
	void set(int arg_row,int arg_col){
		row = arg_row;
		col = arg_col;
	}
	int row,col;
};

struct Info{
	int table[4][8],count;
	Data sace_loc[4];
	Data num_loc[48];
};

map<string,bool> MAP;
int ans_table[4][8];

string makeString(int table[4][8]){

	string ret;
	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			ret.append(to_string(table[row][col])).append(to_string('*'));
		}
	}
	return ret;
}

bool checkClear(int table[4][8]){

	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			if(table[row][col] != ans_table[row][col])return false;
		}
	}

	return true;
}

void copyInfo(Info& to,Info from){

	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			to.table[row][col] = from.table[row][col];
		}
	}

	for(int i = 0; i < 4; i++){
		to.sace_loc[i] = from.sace_loc[i];
	}

	for(int i = 0; i < 48; i++)to.num_loc[i] = from.num_loc[i];
}


void func(){
	MAP.clear();

	Info first;
	first.table[0][0] = 0;
	first.table[1][0] = 0;
	first.table[2][0] = 0;
	first.table[3][0] = 0;

	for(int row = 0; row < 4; row++){
		for(int col = 1; col <= 7; col++){
			scanf("%d",&first.table[row][col]);
			switch(first.table[row][col]){
			case 11:
				first.table[0][0] = 11;
				first.table[row][col] = 0;
				first.sace_loc[0].set(row,col);
				break;
			case 21:
				first.table[1][0] = 21;
				first.table[row][col] = 0;
				first.sace_loc[1].set(row,col);
				break;
			case 31:
				first.table[2][0] = 31;
				first.table[row][col] = 0;
				first.sace_loc[2].set(row,col);
				break;
			case 41:
				first.table[3][0] = 41;
				first.table[row][col] = 0;
				first.sace_loc[3].set(row,col);
				break;
			default:
				first.num_loc[first.table[row][col]].set(row,col);
				break;
			}
		}
	}

	first.count = 0;
	string tmp = makeString(first.table);
	MAP[tmp] = true;

	queue<Info> Q;
	Q.push(first);

	int left_num;

	Data tmp_data;

	while(!Q.empty()){

		if(checkClear(Q.front().table)){
			printf("%d\n",Q.front().count);
			return;
		}else{

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

				left_num = Q.front().table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col-1];

				if(left_num == 0 || left_num%10 == 7)continue;

				tmp_data = Q.front().num_loc[left_num+1];

				Info next_info;
				copyInfo(next_info,Q.front());
				next_info.table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col] = left_num+1;
				next_info.table[tmp_data.row][tmp_data.col] = 0;
				next_info.num_loc[left_num+1].set(Q.front().sace_loc[i].row,Q.front().sace_loc[i].col);

				tmp = makeString(next_info.table);

				auto at = MAP.find(tmp);
				if(at != MAP.end())continue;

				MAP[tmp] = true;
				next_info.sace_loc[i].set(tmp_data.row,tmp_data.col);
				next_info.count = Q.front().count+1;
				Q.push(next_info);
			}
			Q.pop();
		}
	}

	printf("-1\n");
}

int main(){

	for(int col = 0; col <= 6; col++)ans_table[0][col] = 11+col;
	ans_table[0][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[1][col] = 21+col;
	ans_table[1][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[2][col] = 31+col;
	ans_table[2][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[3][col] = 41+col;
	ans_table[3][7] = 0;

	int case_num;
	scanf("%d",&case_num);

	for(int i = 0; i < case_num; i++)func();

}
accuracy: 1
time_ms: 4320
memory_kb: 19232
final_rank: 18

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;

struct Data{
	void set(int arg_row,int arg_col){
		row = arg_row;
		col = arg_col;
	}
	int row,col;
};

struct Info{
	int table[4][8],count;
	Data sace_loc[4];
};

map<string,bool> MAP;
int ans_table[4][8];

string makeString(int table[4][8]){

	string ret;
	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			ret.append(to_string(table[row][col])).append(to_string('*'));
		}
	}
	return ret;
}

bool checkClear(int table[4][8]){

	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			if(table[row][col] != ans_table[row][col])return false;
		}
	}

	return true;
}

void copyInfo(Info& to,Info from){

	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			to.table[row][col] = from.table[row][col];
		}
	}

	for(int i = 0; i < 4; i++){
		to.sace_loc[i] = from.sace_loc[i];
	}
}


void func(){
	MAP.clear();

	Info first;
	first.table[0][0] = 0;
	first.table[1][0] = 0;
	first.table[2][0] = 0;
	first.table[3][0] = 0;

	for(int row = 0; row < 4; row++){
		for(int col = 1; col <= 7; col++){
			scanf("%d",&first.table[row][col]);
			switch(first.table[row][col]){
			case 11:
				first.table[0][0] = 11;
				first.table[row][col] = 0;
				first.sace_loc[0].set(row,col);
				break;
			case 21:
				first.table[1][0] = 21;
				first.table[row][col] = 0;
				first.sace_loc[1].set(row,col);
				break;
			case 31:
				first.table[2][0] = 31;
				first.table[row][col] = 0;
				first.sace_loc[2].set(row,col);
				break;
			case 41:
				first.table[3][0] = 41;
				first.table[row][col] = 0;
				first.sace_loc[3].set(row,col);
				break;
			}
		}
	}

	first.count = 0;
	string tmp = makeString(first.table);
	MAP[tmp] = true;

	queue<Info> Q;
	Q.push(first);

	int left_num,tmp_row,tmp_col;

	while(!Q.empty()){

		if(checkClear(Q.front().table)){
			printf("%d\n",Q.front().count);
			return;
		}else{

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

				left_num = Q.front().table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col-1];

				if(left_num%7 == 0){
					switch(left_num){
					case 17:
						if(Q.front().sace_loc[i].row == 0 && Q.front().sace_loc[i].col == 7)continue;
						break;
					case 27:
						if(Q.front().sace_loc[i].row == 1 && Q.front().sace_loc[i].col == 7)continue;
						break;
					case 37:
						if(Q.front().sace_loc[i].row == 2 && Q.front().sace_loc[i].col == 7)continue;
						break;
					case 47:
						if(Q.front().sace_loc[i].row == 3 && Q.front().sace_loc[i].col == 7)continue;
						break;
					}
				}

				tmp_row = -1;
				for(int row = 0; row < 4; row++){
					for(int col = 0; col < 8; col++){
						if(Q.front().table[row][col] == left_num+1){
							tmp_row = row;
							tmp_col = col;
							break;
						}
					}
					if(tmp_row != -1)break;
				}

				if(tmp_row == -1)continue;

				Info next_info;
				copyInfo(next_info,Q.front());
				next_info.table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col] = left_num+1;
				next_info.table[tmp_row][tmp_col] = 0;

				tmp = makeString(next_info.table);

				auto at = MAP.find(tmp);
				if(at != MAP.end())continue;

				MAP[tmp] = true;
				next_info.sace_loc[i].set(tmp_row,tmp_col);
				next_info.count = Q.front().count+1;
				Q.push(next_info);
			}
			Q.pop();
		}
	}

	printf("-1\n");
}

int main(){

	for(int col = 0; col <= 6; col++)ans_table[0][col] = 11+col;
	ans_table[0][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[1][col] = 21+col;
	ans_table[1][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[2][col] = 31+col;
	ans_table[2][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[3][col] = 41+col;
	ans_table[3][7] = 0;

	int case_num;
	scanf("%d",&case_num);

	for(int i = 0; i < case_num; i++)func();

}
accuracy: 1
time_ms: 4270
memory_kb: 19448
final_rank: 16

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;

struct Data{
	void set(int arg_row,int arg_col){
		row = arg_row;
		col = arg_col;
	}
	int row,col;
};

struct Info{
	int table[4][8],count;
	Data sace_loc[4];
};

map<string,bool> MAP;
int ans_table[4][8];

string makeString(int table[4][8]){

	string ret;
	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			ret.append(to_string(table[row][col])).append(to_string('*'));
		}
	}
	return ret;
}

bool checkClear(int table[4][8]){

	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			if(table[row][col] != ans_table[row][col])return false;
		}
	}

	return true;
}

void copyInfo(Info& to,Info from){

	for(int row = 0; row < 4; row++){
		for(int col = 0; col < 8; col++){
			to.table[row][col] = from.table[row][col];
		}
	}

	for(int i = 0; i < 4; i++){
		to.sace_loc[i] = from.sace_loc[i];
	}
}


void func(){
	MAP.clear();

	Info first;
	first.table[0][0] = 0;
	first.table[1][0] = 0;
	first.table[2][0] = 0;
	first.table[3][0] = 0;

	for(int row = 0; row < 4; row++){
		for(int col = 1; col <= 7; col++){
			scanf("%d",&first.table[row][col]);
			switch(first.table[row][col]){
			case 11:
				first.table[0][0] = 11;
				first.table[row][col] = 0;
				first.sace_loc[0].set(row,col);
				break;
			case 21:
				first.table[1][0] = 21;
				first.table[row][col] = 0;
				first.sace_loc[1].set(row,col);
				break;
			case 31:
				first.table[2][0] = 31;
				first.table[row][col] = 0;
				first.sace_loc[2].set(row,col);
				break;
			case 41:
				first.table[3][0] = 41;
				first.table[row][col] = 0;
				first.sace_loc[3].set(row,col);
				break;
			}
		}
	}

	first.count = 0;
	string tmp = makeString(first.table);
	MAP[tmp] = true;

	queue<Info> Q;
	Q.push(first);

	int left_num,tmp_row,tmp_col;

	while(!Q.empty()){

		if(checkClear(Q.front().table)){
			printf("%d\n",Q.front().count);
			return;
		}else{

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

				left_num = Q.front().table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col-1];

				tmp_row = -1;
				for(int row = 0; row < 4; row++){
					for(int col = 0; col < 8; col++){
						if(Q.front().table[row][col] == left_num+1){
							tmp_row = row;
							tmp_col = col;
							break;
						}
					}
					if(tmp_row != -1)break;
				}

				if(tmp_row == -1)continue;

				Info next_info;
				copyInfo(next_info,Q.front());
				next_info.table[Q.front().sace_loc[i].row][Q.front().sace_loc[i].col] = left_num+1;
				next_info.table[tmp_row][tmp_col] = 0;

				tmp = makeString(next_info.table);

				auto at = MAP.find(tmp);
				if(at != MAP.end())continue;

				MAP[tmp] = true;
				next_info.sace_loc[i].set(tmp_row,tmp_col);
				next_info.count = Q.front().count+1;
				Q.push(next_info);
			}
			Q.pop();
		}
	}

	printf("-1\n");
}

int main(){

	for(int col = 0; col <= 6; col++)ans_table[0][col] = 11+col;
	ans_table[0][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[1][col] = 21+col;
	ans_table[1][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[2][col] = 31+col;
	ans_table[2][7] = 0;
	for(int col = 0; col <= 6; col++)ans_table[3][col] = 41+col;
	ans_table[3][7] = 0;

	int case_num;
	scanf("%d",&case_num);

	for(int i = 0; i < case_num; i++)func();

}
accuracy: 1
time_ms: 4290
memory_kb: 19480
final_rank: 17

code_snippet: /*
 * POJ 2046: Gap
 * ?¢?????????????4?\?1???7?????????????????¨4???8????????????????????°?°?1????????????????????¨?¬¬???????????¶???????¬???????????????????????°?????????§????±?????????????????????§??????????????¨????????\???????????????????±???¨??¨????????????????°?????????\??°???
 * ?±???????BFS
 * ?????????????????¶?????????????¬?????????¨set??????????????????????????¶?????????4????????????????????\???????????°???????????????????????¨????°????????????¬?§????
 */

#include <cstdio>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <unordered_set>

using namespace std;


unordered_set<string> ss;

struct S {
  string s;
  int p[29];
  int b[4];
  int d;

  S() {}

  S(const string &t) : s(t), d(0) {
    int cnt = 0;
    for (int i = 0; i < 32; ++i) {
      if (s[i] == 30) {
        b[cnt++] = i;
      } else {
        p[s[i]] = i;
      }
    }
  }

  S(const S &st) : s(st.s), d(st.d) {
    memcpy(p, st.p, sizeof(p));
    memcpy(b, st.b, sizeof(b));
  }

  bool operator<(const S &st) const {
    return d > st.d;
  }
};

priority_queue<S> pq;


int main() {
  string target(32, ' ');
  int cnt = 0;
  for (int i = 0; i < 4; ++i) {
    for (int j = 1; j <= 7; ++j) {
      target[cnt++] = char(7 * i + j);
    }
    target[cnt++] = char(30);
  }

  int T;
  scanf("%d", &T);
  while (T--) {
    ss.clear();
    while (!pq.empty()) pq.pop();
    cnt = 0;
    string s(32, ' ');
    for (int i = 0; i < 4; ++i) {
      s[cnt++] = char(i * 7 + 1);
      for (int j = 0; j < 7; ++j) {
        int x;
        scanf("%d", &x);
        if (x % 10 == 1) {
          s[cnt++] = char(30);
        } else {
          s[cnt++] = char((x / 10 - 1) * 7 + x % 10);
        }
      }
    }
//    for (int i = 0; i < 32; ++i) printf("%d ", s[i]);printf("\n");

    if (s == target) {
      printf("0\n");
      continue;
    }
    pq.push(S(s));
    int ans = -1;
    while (!pq.empty()) {
      S u(pq.top());
      pq.pop();
      for (int i = 0; i < 4; ++i) {
        int bp = u.b[i];
        char pre = u.s[bp - 1];
        if (pre == 30 || pre % 7 == 0) {
          continue;
        }
        int np = u.p[pre + 1];

        S v(u);
        v.s[bp] = char(pre + 1);
        v.s[np] = char(30);
        if (ss.find(v.s) == ss.end()) {
          ++v.d;
          if (v.s == target) {
//            for (int i = 0; i < 32; ++i) printf("%d ", u.s[i]);
//            printf("---d=%d\n", u.d);
            ans = v.d;
            goto L;
          }
          ss.insert(v.s);
          v.p[pre + 1] = bp;
          v.b[i] = np;
          pq.push(v);
        }
      }
    }
    L:
    printf("%d\n", ans);
  }
  return 0;
}
accuracy: 1
time_ms: 130
memory_kb: 11396
final_rank: 1

code_snippet: #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
using namespace std;
#define REP(i,n) for(int i = 0; i < (int)n; i++)
#define FOR(i,a,b) for(int i = a; i < (int)b; i++)
#define pb push_back
#define mp make_pair
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> pi;
typedef long long ll;
typedef unsigned long long ull;
const int IINF = 1<<28;
const ll MOD = 1000000007;
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};

struct P {
	vvi v;
	int cnt;
	vector<pi> space;
};

bool done(vvi a) {
	REP(i, 4) {
		REP(j, 7) {
			if(a[i][j] != (i+1)*10 + j+1)
				return false;
		}
	}
	return true;
}

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


	int n; cin >> n;
	REP(_, n) {
		set <vvi> s;
		queue<P> q;
		P p;
		p.v.resize(4);
		REP(i, 4) {
			p.v[i].resize(8);
			FOR(j, 1, 8) {
				cin >> p.v[i][j];
				if(p.v[i][j] % 10 == 1) {
					p.v[i][j] = 0;
					p.space.pb(pi(i, j));
				}
			}
		}
		p.v[0][0] = 11;
		p.v[1][0] = 21;
		p.v[2][0] = 31;
		p.v[3][0] = 41;
		p.cnt = 0;
		q.push(p);
		bool flg = false;
		while(q.size()) {
			p = q.front(); q.pop();
			if(done(p.v)) {
				flg = true;
				break;
			}
			REP(i, 4) {
				P p2(p);
				int num = p2.v[p.space[i].first][p.space[i].second-1]+1;
				if(num % 10 == 8)
					continue;
				REP(j, 4) REP(k, 8) {
					if(p2.v[j][k] == num) {
						p2.v[p2.space[i].first][p2.space[i].second] = num;
						p2.v[j][k] = 0;
						p2.space[i] = pi(j, k);
						if(!s.count(p2.v)) {
							p2.cnt++;
							q.push(p2);
							s.insert(p2.v);
						}
						break;
					}
				}
				/*
				REP(j, 4) {
					REP(k, 8)
						cout << p2.v[j][k] << ' ';
					cout << endl;
				}
				*/
			}
		}
		cout << (flg ? p.cnt : -1) << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 930
memory_kb: 25000
final_rank: 9

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

#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=int(a);i<int(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)

#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i)
#define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__)

#define _all(arg) begin(arg),end(arg)
#define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg))
#define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary)
#define clr(a,b) memset((a),(b),sizeof(a))
#define bit(n) (1LL<<(n))
#define popcount(n) (__builtin_popcountll(n))

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

using namespace std;


using state=vector<vector<int>>;
const int inf=1<<29;
const int n=4,m=8;
	
// inline int hstar(const state &board){
// 	int ret=0;
// 	rep(i,n)rep(j,m-1) if(10*(i+1)+j+1!=board[i][j]) ret++;
// 	return ret;
// }

inline bool finish(const state &board){
	rep(i,n)rep(j,m-1) if(10*(i+1)+j+1!=board[i][j]) return false;
	return true;
}

int bfs(const state &board){
	map<state,int> dist;
	using elem=tuple<int,state>;
	priority_queue<elem,vector<elem>,greater<elem>> q;
	
	dist[board]=0;
	q.push(make_tuple(0,board));
	
	while(!q.empty()){
		int cost; state cboard;
		tie(cost,cboard)=q.top();q.pop();
		if(finish(cboard)) return dist[cboard];

		rep(i,n)rep(j,m){
			if(cboard[i][j]==0){
				state nboard=cboard;
				int left=cboard[i][j-1];
				rep(a,n)rep(b,m) if(cboard[a][b]==left+1) swap(nboard[a][b],nboard[i][j]);
				if(dist.find(nboard)!=end(dist)) continue;
				int d=dist[nboard]=dist[cboard]+1;
				q.push(make_tuple(d,nboard));
			}
		}
	}
	return -1;
}

int main(void){
	int t;
	cin >> t;
	while(t--){
		state board(4,vector<int>(8,0));
		rep(i,n)rep(j,1,m) cin >> board[i][j]; 
		rep(i,n)rep(j,m) rep(k,4) if(board[i][j]==10*(k+1)+1) swap(board[i][j],board[k][0]);
		cout << bfs(board) << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 1000
memory_kb: 27672
final_rank: 13

code_snippet: #include <bits/stdc++.h>
 
using namespace std;
 
typedef vector<int> Vec;
typedef pair<Vec,int> P;
 
bool check(Vec &v){
    for(int i = 0 ; i < 32 ; i++){
	if((i+1) % 8 == 0) continue;
	if((i/8+1)*10+i%8+1 != v[i]) return false;
    }
    return true;
}
 
int bfs(Vec &start,Vec &space){
    queue<P> Q;
    queue<Vec> S;
    Q.push(P(start,0));
    S.push(space);
    set<Vec> visited;
    visited.insert(start);
 
    while(!Q.empty()){
	P p = Q.front(); Q.pop();
	Vec s = S.front(); S.pop();
	if(check(p.first)) return p.second;
     
	for(int i = 0 ; i < 4 ; i++){
	    if(p.first[s[i]-1] % 10 == 7) continue;
	    for(int j = 0 ; j < 32 ; j++){
		if(p.first[s[i]-1]+1 == p.first[j]){
		    swap(p.first[s[i]],p.first[j]);
		    int tmp = s[i]; s[i] = j;
		    if(!visited.count(p.first)){
			visited.insert(p.first);
			Q.push(P(p.first,p.second+1));
			S.push(s);
		    }
		    s[i] = tmp;
		    swap(p.first[s[i]],p.first[j]);
		}
	    }
	}
    }
    return -1;
}
 
int main(){
    int Tc;
    cin >> Tc;
    while(Tc--){
	Vec v(32),space;
	for(int i = 0 ; i < 32 ; i++){
	    if(i % 8 != 0){
		cin >> v[i];
		if(v[i]%10 == 1){
		    v[i] = 0;
		    space.push_back(i);
		}
	    }else{
		v[i] = (i/8+1)*10+1;
	    }
	}
	cout << bfs(v,space) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 320
memory_kb: 16812
final_rank: 5

code_snippet: #include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < n; i++)
const int    INF = 100000000;
const double EPS = 1e-10;
const int    MOD = 1000000007;
using namespace std;

struct info{
	vector<vector<int> > v;
	vector<pair<int,int> > b;
};

typedef pair<int,info > P;
typedef pair<int,int> PP;

int n;
vector<vector<int> > v, end;
map<vector<vector<int> >, int> m;
vector<PP> b;

void solve(){
	v.clear(); end.clear(); m.clear(); b.clear();
	v.resize(4);
	rep(i,4) v[i].resize(8);
	end.resize(4);
	rep(i,4) end[i].resize(8);
	rep(i,4) rep(j,8){
		v[i][j] = 0;
		end[i][j] = 0;
	}
	rep(i,4) rep(j,7){
		end[i][j] = (i+1)*10+j+1;
	}
	v[0][0] = 11; v[1][0] = 21; v[2][0] = 31; v[3][0] = 41;
	rep(i,4){
		rep(j,7){
			cin >> v[i][j+1];
			if(v[i][j+1]%10 == 1){
				v[i][j+1] = 0;
				b.push_back(PP(i,j+1));
			}
		}
	}
	queue<P> que;
	info tmp; tmp.v = v; tmp.b = b;
	que.push(P(0,tmp));
	m[v] = 1;
	while(!que.empty()){
		P p = que.front();
		info q = p.second;
		que.pop();
		if(q.v == end){
			cout << p.first << endl;
			return;
		}
		rep(u,q.b.size()){
			int i = q.b[u].first, j = q.b[u].second;
			if(q.v[i][j-1]%10 != 7){
				rep(k,4){
					bool br = false;
					rep(l,8){
						if(q.v[k][l] == q.v[i][j-1]+1){
							q.v[i][j] = q.v[k][l];
							q.v[k][l] = 0;
							if(m[q.v]){
								q.v[k][l] = q.v[i][j];
								q.v[i][j] = 0;
								br = true;
								break;
							}
							m[q.v] = 1;
							q.b[u] = PP(k,l);
							que.push(P(p.first+1,q));
							q.b[u] = PP(i,j);
							q.v[k][l] = q.v[i][j];
							q.v[i][j] = 0;
							br = true;
							break;
						}
					}
					if(br) break;
				}
			}
		}
	}
	cout << "-1" << endl;
}

int main(){
	cin >> n;
	rep(i,n) solve();
}
accuracy: 1
time_ms: 860
memory_kb: 25864
final_rank: 10

code_snippet: #include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class T>
using Table = vector<vector<T>>;
const ld eps=1e-9;

//// < "D:\D_Download\Visual Studio 2015\Projects\programing_contest_c++\Debug\a.txt"
map<vector<vector<int>>, int>mp;

vector<vector<int>>goal;

int getans(const vector<vector<int>>&field) {
	if (field == goal)return 0;
	auto it = mp.find(field);
	if (it != mp.end())return it->second;
	else {
		int ans = 1e5;
		vector<vector<int>>nfield(field);
		for (int i = 0; i < 4; ++i) {
			for (int j = 1; j < 8; ++j) {
				if (!field[i][j]) {
					int from = field[i][j - 1];
					for (int k = 0; k < 4; ++k) {
						for (int l = 0; l < 8; ++l) {
							if (nfield[k][l] == from + 1) {
								swap(nfield[i][j], nfield[k][l]);
								ans = min(getans(nfield) + 1,ans);
								swap(nfield[i][j], nfield[k][l]);
							}
						}
					}
				}
			}
		}
		return mp[field] = ans;
	}
}
int main() {
	int N; cin >> N;
	while (N--) {
		mp.clear();
		vector<vector<int>>field(4, vector<int>(8));
		goal = field;
		for (int i = 0; i < 4; ++i) {
			for (int j = 0; j < 7; ++j) {
				goal[i][j] = 10 * (i + 1) + j + 1;
			}
		}
		for (int i = 0; i < 4; ++i) {
			field[i][0] = i * 10 + 11;
			for (int j = 0; j < 7; ++j) {
				int a; cin >> a;
				if (a % 10 != 1) {
					field[i][j + 1] = a;
				}
			}
		}
		int ans = getans(field);
		if (ans > 9999)ans = -1;
		cout << ans << endl;

	}
	
	
	return 0;
}
accuracy: 1
time_ms: 500
memory_kb: 27660
final_rank: 7

code_snippet: #include <bits/stdc++.h>
 
#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)
 
#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=(int)(a)-1;i>=(int)(b);--i)
#define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__)
 
#define _all(arg) begin(arg),end(arg)
#define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg))
#define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary)
#define clr(a,b) memset((a),(b),sizeof(a))
#define bit(n) (1LL<<(n))
 
// #define DEBUG
 
#ifdef DEBUG
    #define dump(...) fprintf(stderr, __VA_ARGS__)
#else
    #define dump(...)
#endif
 
template<class T>bool chmax(T &a, const T &b) { return (a<b)?(a=b,1):0;}
template<class T>bool chmin(T &a, const T &b) { return (b<a)?(a=b,1):0;}
 
using namespace std;
using ll=long long;
using vi=vector<int>;
using vll=vector<ll>;
 
const double EPS = 1e-10;
const double PI = acos(-1.0);
const ll inf =1LL << 62;
const ll mod=1000000007LL;
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};
 
 
ll extgcd(ll a,ll b,ll& x,ll& y){x=1,y=0;ll g=a;if(b!=0) g=extgcd(b,a%b,y,x),y-=a/b*x;return g;}
ll ADD(const ll &a, const ll &b,const ll &mod) { return (a+b)%mod;}
ll SUB(const ll &a, const ll &b,const ll &mod) { return (a-b+mod)%mod;}
ll MUL(const ll &a, const ll &b,const ll &mod) { return (1LL*a*b)%mod;}
ll DIV(const ll &a, const ll &b,const ll &mod) {ll x,y; extgcd(b,mod,x,y);return MUL(a,(x+mod)%mod,mod);}
 
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dice(1,6);
uniform_real_distribution<double> score(0.0,10.0);
 
using vvi = vector<vi>;

int h = 4, w = 8;

bool check(vvi & board){
    rep(y, h){
        rep(x, w - 1){
            if(board[y][x] != 10 * (y + 1) + (x + 1)) return false;
        }
    }

    return true;
}

int main(void){
    int T; cin >> T;

    while(T--){
        vvi board(h, vi(w));
        rep(y, h){
            rep(x, 1, w){
                cin >> board[y][x];
                if(board[y][x] % 10 == 1){
                    board[y][x] = 0;
                }
            }
        }
        rep(y, h) board[y][0] = 10 * (y + 1) + 1;

        queue<pair<int, vvi>> q;
        map<vvi, bool> used;
        q.push(make_pair(0, board));

        int res = -1;
        while(q.size()){
            vvi cboard = q.front().second;
            int ccost  = q.front().first;
            q.pop();

            if(used[cboard]) continue;
            used[cboard] = true;

            bool ch = false;
            rep(y, h){
                rep(x, 1, w){
                    if(cboard[y][x] != 0 or cboard[y][x - 1] % 10 == 7) continue;

                    [&]{
                        rep(yy, h){
                            rep(xx, w){
                                if(cboard[yy][xx] == cboard[y][x - 1] + 1){
                                    swap(cboard[yy][xx], cboard[y][x]);
                                    if(not used[cboard]){
                                        q.push(make_pair(ccost + 1, cboard));
                                        ch = true;
                                    }
                                    swap(cboard[yy][xx], cboard[y][x]);
                                }
                            }
                        }
                    }();
                }
            }

            if(not ch and check(cboard)){
                res = ccost;
                break;
            }
        }

        cout << res << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 1060
memory_kb: 27984
final_rank: 14

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

string goal[32]={"11","12","13","14","15","16","17","","21","22","23","24","25","26","27","","31","32","33","34","35","36","37","","41","42","43","44","45","46","47",""};

bool check(vector<string> s){
  for(int i=0;i<32;i++)if(s[i]!=goal[i])return false;
  return true;
}

int main()
{
  int n;

  cin>>n;

  for(int k=0;k<n;k++){
    vector<string> f(32);
    for(int i=0;i<4;i++){
      for(int j=0;j<7;j++){
	cin>>f[i*8+j+1];
      }
    }
    for(int i=0;i<32;i++){
      if(f[i]=="11" || f[i]=="21" || f[i]=="31" || f[i]=="41")f[i]="";
    }
    f[0]="11";
    f[8]="21";
    f[16]="31";
    f[24]="41";

    int ans=-1;
    map<vector<string>,int> m;
    queue<vector<string> > q;
    m[f]=0;
    q.push(f);
    while(!q.empty()){
      vector<string> u=q.front();
      q.pop();
      if(check(u)){
	ans=m[u];
	break;
      }
      for(int i=0;i<32;i++){
	if(u[i]==""){
	  vector<string> t=u;
	  if(t[i-1]=="" || t[i-1][1]=='7')continue;
	  string s=t[i-1];
	  s[1]++;
	  for(int j=0;j<32;j++){
	    if(t[j]==s){
	      t[j]="";
	      break;
	    }
	  }
	  t[i]=s;
	  if(m.find(t)==m.end()){
	    m[t]=m[u]+1;
	    q.push(t);
	  }
	}
      }
    }
    cout<<ans<<endl;
  }
}
accuracy: 1
time_ms: 3680
memory_kb: 35776
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef vector<vector<int> > Mat;
#define getMat(r, c) Mat(r, vector<int>(c));

const int INF = 1<<28;
const int R = 4;
const int C = 8;

Mat G = getMat(R, C);
map<Mat, int> mem;

void show() {
  for (int i = 0; i < R; ++i) {
    for (int j = 0; j < C; ++j) {
      if (j) cout << " ";
      if (G[i][j] == 0) cout << "00";
      else cout << G[i][j];
    }
    cout << endl;
  }
}

int diff() {
  int res = 0;
  for (int i = 0; i < R; ++i) {
    for (int j = 0; j < C-1; ++j) {
      if (G[i][j] != (i+1) * 10 + (j+1)) {
        ++res;
      }
    }
  }
  return res;
}

int rec() {
  if (mem.count(G)) return mem[G];
  if (diff() == 0) {
    return mem[G] = 0;
  }
  //show(); cout << endl;
  int res = INF;
  for (int i = 0; i < R; ++i) {
    for (int j = 0; j < C; ++j) {
      if (G[i][j] != 0) continue;
      if (G[i][j-1] == 0) continue;
      if (G[i][j-1] % 10 == 7) continue;
      int target = G[i][j-1] + 1;
      try {
        for (int i2 = 0; i2 < R; ++i2) {
          for (int j2 = 0; j2 < C; ++j2) {
            if (G[i2][j2] == target) {
              swap(G[i][j], G[i2][j2]);
              res = min(res, rec() + 1);
              swap(G[i][j], G[i2][j2]);
              throw 0;
            }
          }
        }
      } catch(...) {}
    }
  }
  return mem[G] = res;
}

int main() {
  int Tc;
  cin >> Tc;
  while (Tc--) {
    for (int i = 0; i < R; ++i) {
      G[i][0] = (i+1)*10 + 1;
      for (int j = 1; j < C; ++j) {
        cin >> G[i][j];
        if (G[i][j] % 10 == 1) G[i][j] = 0;
      }
    }
    mem.clear();
    int res = rec();
    if (res == INF) res = -1;
    cout << res << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 2050
memory_kb: 25824
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (k); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
#define D10 fixed<<setprecision(10)
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
typedef long double ld;
const int MOD = 1000000007;
const int INF = MOD + 1;
const ld EPS = 1e-10;
template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }

/*--------------------template--------------------*/

int main()
{
	int n;
	cin >> n;
	while (n--)
	{
		vector<vi> v(4, vi(8));
		auto goal = v;
		REP(i, 4)REP(j, 7) goal[i][j] = (i+1) * 10 + j + 1;
		REP(i, 4)FOR(j, 1, 8)
		{
			cin >> v[i][j];
			if (v[i][j] % 10 == 1)
			{
				v[v[i][j] / 10 - 1][0] = v[i][j];
				v[i][j] = 0;
			}
		}
		queue<pair<vector<vi>, int>> que;
		set<vector<vi>> st;
		que.push(make_pair(v, 0));
		bool f = true;
		while (que.size())
		{
			auto tmp = que.front().first;
			int cnt = que.front().second;
			que.pop();
			if (tmp == goal)
			{
				f = false;
				cout << cnt << endl;
				break;
			}
			REP(i, 4)FOR(j, 1, 8)
			{
				if (tmp[i][j] == 0 && tmp[i][j - 1] != 0 && tmp[i][j - 1] % 10 != 7)
				{
					auto nx = tmp;
					int t = tmp[i][j - 1] + 1;
					REP(ii, 4)REP(jj, 8)
					{
						if (tmp[ii][jj] == t)
						{
							nx[ii][jj] = 0;
						}
					}
					nx[i][j] = t;
					if (st.count(nx)) continue;
					else
					{
						st.insert(nx);
						que.push(make_pair(nx, cnt + 1));
					}
				}
			}
		}
		if (f) puts("-1");
	}
	return 0;
}
accuracy: 1
time_ms: 660
memory_kb: 26364
final_rank: 8

code_snippet: #include <cstdio>
#include <cstring>
#include <map>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;
typedef vector<int> vec;
typedef vector<vec > mal;
int ttt;
mal g(4,vector<int>(8));
map<mal,int> dist;
set<mal> checked;

bool check(mal c){
	for(int i=0;i<4;i++){
		for(int j=0;j<7;j++){
			if(c[i][j]!=(i+1)*10+j+1)return false;
		}
	}
	return true;
}

int bfs(mal s){
	checked.clear();
	dist.clear();
	queue<mal > que;
	que.push(s);
	checked.insert(s);
	while(que.size()){
		mal q=que.front();
		que.pop();
		if(check(q))return dist[q];
		for(int i=0;i<4;i++){
			for(int j=1;j<8;j++){
				if(q[i][j]!=0)continue;
				for(int k=0;k<4;k++){
					for(int l=1;l<8;l++){
						if(q[k][l]==0)continue;
						if(q[i][j-1]==q[k][l]-1){
							mal nq=q;
							nq[i][j]=q[k][l];
							nq[k][l]=0;
							if(checked.find(nq)==checked.end()){
								checked.insert(nq);
								dist[nq]=dist[q]+1;
								que.push(nq);
							}
						}	
					}
				}
			}
		}
	}
	return -1;
}

int main(void){
	scanf("%d",&ttt);
	for(int test=0;test<ttt;test++){
		mal fie(4,vec(8));
		for(int i=0;i<4;i++){
			for(int j=1;j<8;j++){
				scanf("%d",&fie[i][j]);
				if(fie[i][j]%10==1){
					fie[fie[i][j]/10-1][0]=fie[i][j];
					fie[i][j]=0;
				}
			}
		}
		printf("%d\n",bfs(fie));
	}
	return 0;
}
accuracy: 1
time_ms: 1430
memory_kb: 49248
final_rank: 19

code_snippet: //include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
#include <queue>

using namespace std;

//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;

//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())

//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);

int idx(PII p){
  return p.first*10+p.second+11;
}

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

  int N; cin >> N;
  REP(n,N){
	VI xs(32);
	REP(i,4){
	  REP(j,7) cin >> xs[i*8+j+1];
	  xs[i*8] = 0;
	}

	REP(i,32)
	  if(xs[i]%10 == 1){
		swap(xs[i], xs[(xs[i]/10-1)*8]);
	  }

	map<VI,int> memo;
	queue<VI> q;
	q.push(xs);
	memo[xs] = 0;

	int ans = -1;
	while(!q.empty()){
	  xs = q.front(); q.pop();
	  bool ok = true;
	  REP(y,4) REP(x,7)
		if(xs[y*8+x] != y*10+x+11){
		  ok = false;
		  x = y = 100;
		}
	  if(ok){
		ans = memo[xs];
		break;
	  }

	  int d = memo[xs];
	  REP(y,4) FOR(x,1,8){
		int idx = y*8+x;
		if(xs[idx] == 0 && xs[idx-1]%10 < 7){
		  REP(ty,4) FOR(tx,1,8){
			int tidx = ty*8+tx;
			if(xs[idx-1]+1 == xs[tidx]){
			  VI tmp = xs;
			  swap(tmp[idx], tmp[tidx]);

			  if(!memo.count(tmp)){
				q.emplace(tmp);
				memo[tmp] = d + 1;
			  }
			  ty = tx = 100;
			}
		  }
		}
	  }
	}
	cout << ans << endl;
  }

  return 0;
}
accuracy: 1
time_ms: 500
memory_kb: 15984
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef vector< int > vec;
typedef vector< vec > mat;
map < mat , int > d;

int solve(mat A){
  queue< mat > Q;
  Q.push(A);
  

    
  d[A]=1;
  while(!Q.empty()){
    mat a=Q.front();Q.pop();
   
    bool f=true;
    
    for(int i=0;i<4;i++){
      for(int j=0;j<8;j++){
        if(a[i][j]!=0&&i*10+10+j+1!=a[i][j]){
          f=false;
        }
      }
    }
    if(f)return d[a]-1;

    for(int i=0;i<4;i++){
      for(int j=1;j<8;j++){
        if(a[i][j]!=0)continue;
        
        mat b=a;
        int c=a[i][j-1]+1;

        int h=-1,w;
        for(int k=0;k<4;k++){
          for(int l=0;l<8;l++){
            if(b[k][l]==c){
              h=k,w=l;
            }
          }
        }

        if(h==-1)continue;

        swap(b[h][w],b[i][j]);

        if(d[b]==0){
          d[b]=d[a]+1;
          Q.push(b);
        }
      }
    }

  }
  return -1;
}

int main(){
  int Tc;
  cin>>Tc;
  while(Tc--){
    d.clear();
    mat A(4, vec(8) );
    for(int i=0;i<4;i++){
      A[i][0]=i*10+10+1;
      for(int j=0;j<7;j++){
        cin>>A[i][j+1];
        if(A[i][j+1]%10==1)A[i][j+1]=0;
      }
    }
    cout<<solve(A)<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 1070
memory_kb: 25832
final_rank: 11