Problem:
7 パズル
7 パズルは 8 つの正方形のカードとこれらのカードがぴたりと収まる枠で構成されています。それぞれのカードには、互いに区別できるように 0, 1, 2, ..., 7 と番号がつけられています。枠には、縦に 2 個、横に 4 個のカードを並べることができます。
7 パズルを始めるときには、まず枠にすべてのカードを入れます。枠のなかで 0 のカードだけは、上下左右に隣接するカードと位置を交換することができます。たとえば、枠の状態が図(a) のときに、0 のカードの右に隣接した、7 のカードと位置を交換すれば、図(b) の状態になります。あるいは、図(a) の状態から 0 のカードの下に隣接した 2 のカードと位置を交換すれば図(c) の状態になります。図(a) の状態で 0 のカードと上下左右に隣接するカードは 7 と 2 のカードだけなので、これ以外の位置の入れ替えは許されません。
ゲームの目的は、カードをきれいに整列して図(d) の状態にすることです。最初の状態を入力とし、カードをきれいに整列するまでに、必要な最小手数を出力するプログラムを作成してください。ただし、入力されたカードの状態からは図(d) の状態に移ることは可能であるとします。
入力データは、1 行に 8 つの数字が空白区切りで与えられます。これらは、最初の状態のカードの並びを表します。例えば、図(a) の数字表現は
0 7 3 4 2 5 1 6
に、図(c) は
2 7 3 4 0 5 1 6
となります。
図(a)
0 7 3 4 2 5 1 6
の場合
図(b)
7 0 3 4 2 5 1 6
の場合
図(c)
2 7 3 4 0 5 1 6
の場合
図(d)
0 1 2 3 4 5 6 7
(最終状態)
Input
上記形式で複数のパズルが与えられます。入力の最後まで処理してください。
与えられるパズルの数は 1,000 以下です。
Output
各パズルについて、最終状態へ移行する最小手数を１行に出力してください。
Sample Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output for the Sample Input
0
1
28

Submitted solutions:

code_snippet: // #pragma GCC target("avx2")
// #pragma GCC optimize("O3")
// #pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
using namespace std;

using ll=long long;
using ld=long double;
using pl=pair<ll,ll>;
using vpl=vector<pl>;
using vl=vector<ll>;
using vvl=vector<vl>;

#define rep(i,n) for(long long i=0LL;i<n;i++)
#define rrep(i,a,b) for(long long i=a;i>=b;i--)
#define FOR(i,k,n) for(long long i=k;i<n;i++)
#define ALL(v) v.begin(),v.end()
template<typename T>ostream&operator<<(ostream& os,vector<T>&v){for(int i = 0;i < int(size(v));i++)os << v[i] << (i+1==int(size(v))?"":" ");return os;}
template<typename T>istream&operator>>(istream& is,vector<T>&v){for(auto &in : v)is >> in;return is;}
ll INF = (1LL << 60) - 6846976;
/* INF = (1LL << 60) - 6846976*/


// #include<atcoder/all> 
// using namespace atcoder;
// using mint = modint998244353;ll mod = 998244353;
// // using mint = modint1000000007;ll mod = 1000000007;
// //using mint = modint;
// using vm = vector<mint>;
// using vvm = vector<vm>;
// ostream&operator<<(ostream& os,vector<mint>&v){for(int i = 0;i < int(size(v));i++)os << v[i].val() << (i+1==int(size(v))?"":" ");return os;}

#define LB(A,x) int(lower_bound(ALL(A),x)-A.begin())



// vl dx = {1,0,-1,0}, dy = {0,1,0,-1};
// vl dx = {1,1,1,0,-1,-1,-1,0},dy={-1,0,1,1,-1,0,1,-1};
//----------------------------------------------


int main(){
  ios::sync_with_stdio(false);cin.tie(nullptr);cout<<fixed<<setprecision(15);
//==============================================
  vl A(8);
  vl vec(8);
  map<vl,ll> mp;
  ll sz=0;
  iota(ALL(vec),0LL);
  vvl to(100009);
  do{
    mp[vec]=sz++;
  }while(next_permutation(ALL(vec)));
  do{
    vl tmp = vec;
    rep(i,8) if(vec[i]==0){
      if(i<4){
        swap(tmp[i],tmp[i+4]);
        to[mp[vec]].push_back(mp[tmp]);
        to[mp[tmp]].push_back(mp[vec]);
        swap(tmp[i],tmp[i+4]);
      }
      if(i%4!=3){
        swap(tmp[i],tmp[i+1]);
        to[mp[vec]].push_back(mp[tmp]);
        to[mp[tmp]].push_back(mp[vec]);
        swap(tmp[i],tmp[i+1]);
      }
    }
  }while(next_permutation(ALL(vec)));


  while(cin>>A[0]){
    FOR(i,1,8) cin>>A[i];
    queue<ll> que;
    vl dist(mp.size(),INF);
    dist[mp[A]]=0;
    que.push(mp[A]);
    while(que.size()){
      ll v = que.front(); que.pop();
      for(ll nv : to[v]){
        if(dist[nv]>dist[v]+1){
          dist[nv]=dist[v]+1;
          que.push(nv);
        }
      }
    }
    cout<<dist[0]<<endl;

  }


}
accuracy: 1
time_ms: 460
memory_kb: 13600
final_rank: 18

code_snippet: #include <iostream>
#include <algorithm>
#include <map>
#include <queue>

using namespace std;

map<string,int> dp;
int dx[]={-1,1,4,-4};

void BFS()
{
	queue<string> que;

	dp["01234567"]=0;
	que.push("01234567");

	while(!que.empty())
	{
		string strbak=que.front();
		que.pop();

		int pos=strbak.find('0');

		for(int i=0;i<4;i++)
		{
			int npos=pos+dx[i];

			if((npos<0 || npos>=8) || (pos==3 && npos==4) || (npos==3 && pos==4)) continue;
			string strtmp=strbak;
            swap(strtmp[pos],strtmp[npos]);
            if(dp.find(strtmp)==dp.end())
            {
				dp[strtmp]=dp[strbak]+1;
				que.push(strtmp);
			}
		}
	}
}

int main()
{
	BFS();

	string str;
	while(getline(cin,str))
	{
		str.erase(remove(str.begin(),str.end(),' '),str.end());
		cout<<dp[str]<<endl;
	}

	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4924
final_rank: 4

code_snippet: #include<stdio.h>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
map<int,int> bfs;
int a[8];
int main(){
	bfs[342391]=0;
	queue<int>Q;
	Q.push(342391);
	while(Q.size()){
		int at=Q.front();
		Q.pop();
		int zero;
		for(int i=0;i<8;i++)if((at%(8<<(3*i))/(1<<(3*i)))==0)zero=i;
		if(zero%4){
			if(!bfs.count(at-(at%(8<<(3*(zero-1)))/(1<<(3*(zero-1))))*(1<<(3*(zero-1)))+(at%(8<<(3*(zero-1)))/(1<<(3*(zero-1))))*(1<<(3*zero)))){
				bfs[at-(at%(8<<(3*(zero-1)))/(1<<(3*(zero-1))))*(1<<(3*(zero-1)))+(at%(8<<(3*(zero-1)))/(1<<(3*(zero-1))))*(1<<(3*zero))]=bfs[at]+1;
				Q.push(at-(at%(8<<(3*(zero-1)))/(1<<(3*(zero-1))))*(1<<(3*(zero-1)))+(at%(8<<(3*(zero-1)))/(1<<(3*(zero-1))))*(1<<(3*zero)));
			}
		}
		if(zero%4!=3){
			if(!bfs.count(at-(at%(8<<(3*(zero+1)))/(1<<(3*(zero+1))))*(1<<(3*(zero+1)))+(at%(8<<(3*(zero+1)))/(1<<(3*(zero+1))))*(1<<(3*zero)))){
				bfs[at-(at%(8<<(3*(zero+1)))/(1<<(3*(zero+1))))*(1<<(3*(zero+1)))+(at%(8<<(3*(zero+1)))/(1<<(3*(zero+1))))*(1<<(3*zero))]=bfs[at]+1;
				Q.push(at-(at%(8<<(3*(zero+1)))/(1<<(3*(zero+1))))*(1<<(3*(zero+1)))+(at%(8<<(3*(zero+1)))/(1<<(3*(zero+1))))*(1<<(3*zero)));
			}
		}
		if(!bfs.count(at-(at%(8<<(3*(zero^4)))/(1<<(3*(zero^4))))*(1<<(3*(zero^4)))+(at%(8<<(3*(zero^4)))/(1<<(3*(zero^4))))*(1<<(3*zero)))){
			bfs[at-(at%(8<<(3*(zero^4)))/(1<<(3*(zero^4))))*(1<<(3*(zero^4)))+(at%(8<<(3*(zero^4)))/(1<<(3*(zero^4))))*(1<<(3*zero))]=bfs[at]+1;
			Q.push(at-(at%(8<<(3*(zero^4)))/(1<<(3*(zero^4))))*(1<<(3*(zero^4)))+(at%(8<<(3*(zero^4)))/(1<<(3*(zero^4))))*(1<<(3*zero)));
		}
	}
	while(~scanf("%d",a)){
		for(int i=1;i<8;i++)scanf("%d",a+i);
		//bfs.clear();
		int t=0;
		for(int i=0;i<8;i++){
			t*=8;
			t+=a[i];
		}
		printf("%d\n",bfs[t]);
	}
}
accuracy: 1
time_ms: 10
memory_kb: 3740
final_rank: 1

code_snippet: #include <iostream>
#include <sstream>
#include <map>
#include <queue>
#include <string>

using namespace std;

map<string, int> mp;
string curstr, net;
int prefix[4] = {-1, -4, 1, 4};


void bfs() {
    string ori = "01234567";
    mp[ori] = 0;
    queue<string> que; que.push(ori);

    while(que.size()) {
        curstr = que.front();
        que.pop();

        int index_0 = curstr.find("0");
        for (int i = 0; i < 4; i++) {
            if ((index_0 == 3 && i == 2) || (index_0 == 4 && i == 0)) {
                continue;
            }

            net = curstr;
            int target = index_0 + prefix[i];
            if (target >= 0 && target < net.size()) {
                net.replace(index_0, 1, net.substr(target, 1));
                net.replace(target, 1, "0");

                if (!mp.count(net)) {
                    mp[net] = mp[curstr] + 1;
                    que.push(net);
                }
            }
        }
    }
}

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

    bfs();
    string result = "";
    string start;
    while (getline(cin, start)) {
        if (start == "") {
            break;
        }

        istringstream iss(start);
        string str;
        for (int i = 0; i < 8; i++) {
            iss >> str;
            result += str;
        }

        cout << mp[result] << '\n';
        start = "";
        result = "";
    }

    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4944
final_rank: 6

code_snippet: #include "bits/stdc++.h"
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
#define rep(i, m, n) for (ll i = (ll)m; i < (ll)n; i++)
#define drep(i, m, n) for (ll i = m - 1; i >= n; i--)
#define Endl endl
#define all(a) a.begin(), a.end()
#define pr(i, j) make_pair(i, j)
#define isin(x, l, r) (l <= x && x < r)
#define chmin(a, b) a = min(a, b)
#define chmax(a, b) a = max(a, b)
#define srt(ar) sort(ar.begin(), ar.end())
#define rev(ar) reverse(ar.begin(), ar.end())
#define jge(f, s, t) cout << (f ? s : t) << endl
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#define printar(ar)             \
    do                          \
    {                           \
        for (auto dbg : ar)     \
        {                       \
            cout << dbg << " "; \
        }                       \
        cout << endl;           \
    } while (0)
const ll inf = 1e18;
const ld pi = 3.14159265358979;
const ld eps = 1e-9;
template <class T, ll n, ll idx = 0>
auto make_vec(const ll (&d)[n], const T &init) noexcept
{
    if constexpr (idx < n)
        return std::vector(d[idx], make_vec<T, n, idx + 1>(d, init));
    else
        return init;
}

template <class T, ll n>
auto make_vec(const ll (&d)[n]) noexcept
{
    return make_vec(d, T{});
}
//////////////// 以下を貼る ////////////////
template <class T>
size_t HashCombine(const size_t seed, const T &v)
{
    return seed ^ (std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
}
/* pair用 */
template <class T, class S>
struct std::hash<std::pair<T, S>>
{
    size_t operator()(const std::pair<T, S> &keyval) const noexcept
    {
        return HashCombine(std::hash<T>()(keyval.first), keyval.second);
    }
};
////////////////////////////////////////////
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    queue<ll> q;
    ll x;
    while (cin >> x)
    {
        q.push(x);
    }
    map<vector<vector<ll>>, ll> mp;
    map<vector<vector<ll>>, bool> v;
    queue<vector<vector<ll>>> bfs;
    vector<vector<ll>> ini = {{0, 1, 2, 3}, {4, 5, 6, 7}};
    bfs.push(ini);
    mp[ini] = 0;
    v[ini] = true;
    while (!bfs.empty())
    {
        vector<vector<ll>> now = bfs.front();
        bfs.pop();
        ll x = -1, y = -1;
        rep(i, 0, 2)
        {
            rep(j, 0, 4)
            {
                if (now[i][j] == 0)
                {
                    x = i;
                    y = j;
                }
            }
        }
        vector<ll> dx = {1, 0, -1, 0};
        vector<ll> dy = {0, -1, 0, 1};
        rep(i, 0, 4)
        {
            ll nx = x + dx[i];
            ll ny = y + dy[i];
            vector<vector<ll>> nxt = now;
            if (isin(nx, 0, 2) && isin(ny, 0, 4))
            {
                swap(nxt[x][y], nxt[nx][ny]);
            }
            if (!v[nxt])
            {
                v[nxt] = true;
                mp[nxt] = mp[now] + 1;
                bfs.push(nxt);
            }
        }
    }
    while (!q.empty())
    {
        vector<vector<ll>> ar(2, vector<ll>(4));
        rep(i, 0, 8)
        {
            ar[i / 4][i % 4] = q.front();
            q.pop();
        }
        cout << mp[ar] << endl;
    }
}
accuracy: 1
time_ms: 30
memory_kb: 13184
final_rank: 17

code_snippet: #include <iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#include<stack>
#include<set>
#include<map>
#include<cstdio>
#include<iomanip>
#include<sstream>
using namespace std;
#define ll long long

const int mod = 998244353;
const int N = 4e6 + 10;
const int M = 1e5 + 10;
const int inf = 0x3f3f3f3f;

int t, l, r, ans = inf, ex, sy;
ll k, x, n, cnt;
map<string, int>m;
int run[4] = { 1,-1,4,-4 };

void bfs() {
	queue<string>q;
	q.push("01234567");
	while (!q.empty()) {
		string now = q.front();
		q.pop();
		int p = 0;
		for (int i = 0; i < 8; i++)
			if (now[i] == '0')
				p = i;
		for (int i = 0; i < 4; i++) {
			int np = p + run[i];
			string nxt=now;
			if (np >= 0 && np < 8 && !(p == 3 && np == 4) && !(p == 4 && np == 3))
			{
				swap(nxt[p], nxt[np]);
				if (m.find(nxt) == m.end()) {
					m[nxt] = m[now] + 1;
					q.push(nxt);
				}
			}
		}
	}
}

void solve() {
	string s;
	m["01234567"] = 0;
	bfs();
	while (getline(cin,s)) {
		s.erase(remove(s.begin(), s.end(),' '), s.end());
		cout << m[s] << endl;
	}
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	t = 1;
	//cin >> t;
	while (t--)
		solve();

	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4984
final_rank: 7

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

using namespace std;

// 目标状态
const string goal = "01234567";

// 方向数组，表示0可以移动的四个方向（上、下、左、右）
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};

// 将状态转换为字符串
string to_string(const vector<int>& state) {
    string s;
    for (int num : state) {
        s += to_string(num);
    }
    return s;
}

// 找到0的位置
pair<int, int> find_zero(const string& state) {
    for (int i = 0; i < 8; ++i) {
        if (state[i] == '0') {
            return {i / 4, i % 4};
        }
    }
    return {-1, -1}; // 不应该发生
}

// 检查位置是否在边界内
bool in_bounds(int x, int y) {
    return x >= 0 && x < 2 && y >= 0 && y < 4;
}

// 双向BFS搜索
int bidirectional_bfs(const string& start) {
    queue<string> q1, q2;
    unordered_map<string, int> dist1, dist2;

    q1.push(start);
    dist1[start] = 0;

    q2.push(goal);
    dist2[goal] = 0;

    while (!q1.empty() && !q2.empty()) {
        // 从初始状态扩展
        string current1 = q1.front();
        q1.pop();

        if (dist2.find(current1) != dist2.end()) {
            return dist1[current1] + dist2[current1];
        }

        auto [x1, y1] = find_zero(current1);
        int zero_index1 = x1 * 4 + y1;

        for (int d = 0; d < 4; ++d) {
            int nx1 = x1 + dx[d];
            int ny1 = y1 + dy[d];

            if (in_bounds(nx1, ny1)) {
                int new_index1 = nx1 * 4 + ny1;
                string next1 = current1;
                swap(next1[zero_index1], next1[new_index1]);

                if (dist1.find(next1) == dist1.end()) {
                    dist1[next1] = dist1[current1] + 1;
                    q1.push(next1);
                }
            }
        }

        // 从目标状态扩展
        string current2 = q2.front();
        q2.pop();

        if (dist1.find(current2) != dist1.end()) {
            return dist1[current2] + dist2[current2];
        }

        auto [x2, y2] = find_zero(current2);
        int zero_index2 = x2 * 4 + y2;

        for (int d = 0; d < 4; ++d) {
            int nx2 = x2 + dx[d];
            int ny2 = y2 + dy[d];

            if (in_bounds(nx2, ny2)) {
                int new_index2 = nx2 * 4 + ny2;
                string next2 = current2;
                swap(next2[zero_index2], next2[new_index2]);

                if (dist2.find(next2) == dist2.end()) {
                    dist2[next2] = dist2[current2] + 1;
                    q2.push(next2);
                }
            }
        }
    }

    return -1; // 不应该发生
}

int main() {
    int num;
    while (cin >> num) {
        vector<int> initial_state(8);
        initial_state[0] = num;
        for (int i = 1; i < 8; ++i) {
            cin >> initial_state[i];
        }

        string start = to_string(initial_state);
        int result = bidirectional_bfs(start);
        cout << result << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 240
memory_kb: 3836
final_rank: 13

code_snippet: #include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <string>
#include <algorithm>

using namespace std;

// 目标状态
const string goal = "01234567";

// 方向数组，表示0可以移动的四个方向（上、下、左、右）
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};

// 将状态转换为字符串
string to_string(const vector<int>& state) {
    string s;
    for (int num : state) {
        s += to_string(num);
    }
    return s;
}

// 找到0的位置
pair<int, int> find_zero(const string& state) {
    for (int i = 0; i < 8; ++i) {
        if (state[i] == '0') {
            return {i / 4, i % 4};
        }
    }
    return {-1, -1}; // 不应该发生
}

// 检查位置是否在边界内
bool in_bounds(int x, int y) {
    return x >= 0 && x < 2 && y >= 0 && y < 4;
}

// 双向BFS搜索
int bidirectional_bfs(const string& start) {
    queue<string> q1, q2;
    unordered_map<string, int> dist1, dist2;

    q1.push(start);
    dist1[start] = 0;

    q2.push(goal);
    dist2[goal] = 0;

    while (!q1.empty() && !q2.empty()) {
        // 从初始状态扩展
        string current1 = q1.front();
        q1.pop();

        if (dist2.find(current1) != dist2.end()) {
            return dist1[current1] + dist2[current1];
        }

        auto [x1, y1] = find_zero(current1);
        int zero_index1 = x1 * 4 + y1;

        for (int d = 0; d < 4; ++d) {
            int nx1 = x1 + dx[d];
            int ny1 = y1 + dy[d];

            if (in_bounds(nx1, ny1)) {
                int new_index1 = nx1 * 4 + ny1;
                string next1 = current1;
                swap(next1[zero_index1], next1[new_index1]);

                if (dist1.find(next1) == dist1.end()) {
                    dist1[next1] = dist1[current1] + 1;
                    q1.push(next1);
                }
            }
        }

        // 从目标状态扩展
        string current2 = q2.front();
        q2.pop();

        if (dist1.find(current2) != dist1.end()) {
            return dist1[current2] + dist2[current2];
        }

        auto [x2, y2] = find_zero(current2);
        int zero_index2 = x2 * 4 + y2;

        for (int d = 0; d < 4; ++d) {
            int nx2 = x2 + dx[d];
            int ny2 = y2 + dy[d];

            if (in_bounds(nx2, ny2)) {
                int new_index2 = nx2 * 4 + ny2;
                string next2 = current2;
                swap(next2[zero_index2], next2[new_index2]);

                if (dist2.find(next2) == dist2.end()) {
                    dist2[next2] = dist2[current2] + 1;
                    q2.push(next2);
                }
            }
        }
    }

    return -1; // 不应该发生
}

int main() {
    int num;
    while (cin >> num) {
        vector<int> initial_state(8);
        initial_state[0] = num;
        for (int i = 1; i < 8; ++i) {
            cin >> initial_state[i];
        }

        string start = to_string(initial_state);
        int result = bidirectional_bfs(start);
        cout << result << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 240
memory_kb: 3844
final_rank: 14

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

int visited[8][8][8][8][8][8][8];

int direction[] = {-1, 1, 4, -4};

struct PuzzleState {
    int tiles[8];
    int moves;
    PuzzleState(int* initialTiles, int moveCount) {
        for (int i = 0; i < 8; i++)
            tiles[i] = initialTiles[i];
        moves = moveCount;
    }
};

bool hasVisited(int* currentTiles) {
    return visited[currentTiles[0]][currentTiles[1]][currentTiles[2]][currentTiles[3]][currentTiles[4]][currentTiles[5]][currentTiles[6]] == 1;
}

void markVisited(int* currentTiles) {
    visited[currentTiles[0]][currentTiles[1]][currentTiles[2]][currentTiles[3]][currentTiles[4]][currentTiles[5]][currentTiles[6]] = 1;
}

bool isGoalState(int* currentTiles) {
    for (int i = 0; i < 7; i++)
        if (currentTiles[i] != i)
            return false;
    return true;
}

int bfs(int* initialTiles) {
    queue<PuzzleState> queue;
    queue.push(PuzzleState(initialTiles, 0));
    markVisited(initialTiles);
    
    while (!queue.empty()) {
        PuzzleState currentState = queue.front();
        queue.pop();
        int tempTiles[8]; // Temporary array to store current state
        int zeroPosition = 0; // Record the position of the zero tile

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 8; j++)
                tempTiles[j] = currentState.tiles[j];
            for (int j = 0; j < 8; j++)
                if (tempTiles[j] == 0) zeroPosition = j;

            int newPosition = zeroPosition + direction[i];
            if (newPosition < 0 || newPosition > 7) continue;
            if (zeroPosition == 3 && newPosition == 4) continue;
            if (zeroPosition == 4 && newPosition == 3) continue;

            swap(tempTiles[newPosition], tempTiles[zeroPosition]);
            if (isGoalState(tempTiles)) return currentState.moves + 1; // Found the goal state
            if (hasVisited(tempTiles)) continue; // If this state has been visited

            queue.push(PuzzleState(tempTiles, currentState.moves + 1)); // Add new state to queue
            markVisited(tempTiles); // Mark this state as visited
        }
    }
    return -1; // Should not reach here if the input is valid
}

int main() {
    int tiles[8];
    while (scanf("%d", &tiles[0]) != EOF) {
        memset(visited, 0, sizeof(visited));
        for (int i = 1; i < 8; i++)
            scanf("%d", &tiles[i]);

        if (isGoalState(tiles)) cout << 0 << endl;
        else cout << bfs(tiles) << endl;
    }
}
accuracy: 1
time_ms: 860
memory_kb: 11432
final_rank: 20

code_snippet: #include <iostream>
#include <queue>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
 
int vis[8][8][8][8][8][8][8];
 
int d[]={-1,1,4,-4};
 
struct node
{
    int a[8];
    int time;
    node(int * b,int ti)//深拷贝
    {
        for(int i=0;i<8;i++)
            a[i]=b[i];
        time=ti;
    }
};
 
bool judge(int * a1)//判断是否访问过这种状态
{
    if(vis[a1[0]][a1[1]][a1[2]][a1[3]][a1[4]][a1[5]][a1[6]]==1)
        return true;
    return false;
}
 
void update(int * a1)
{
    vis[a1[0]][a1[1]][a1[2]][a1[3]][a1[4]][a1[5]][a1[6]]=1;
}
 
bool is_ans(int * b)
{
    for(int i=0;i<7;i++)
        if(b[i]!=i)
        return false;
    return true;
}
 
int bfs(int * a1)
{
    queue<node> que;
    que.push(node(a1,0));
    vis[a1[0]][a1[1]][a1[2]][a1[3]][a1[4]][a1[5]][a1[6]]=1;
    while(!que.empty())
    {
        node no=que.front();
        que.pop();
        int b[8];//临时数组用来保存no的数据
        int p=0;//记录0的位置
 
 
        for(int i=0;i<4;i++)
        {
            for(int i=0;i<8;i++)
            b[i]=no.a[i];
            for(int i=0;i<8;i++)
            if(b[i]==0)p=i;
            int x=p+d[i];
            if(x<0||x>7)continue ;
            if(p==3&&x==4)continue;
            if(p==4&&x==3)continue;
            swap(b[x],b[p]);
            if(is_ans(b))return no.time+1;//找到最终状态
            if(judge(b))continue;//如果这种状态处理过了
            que.push(node(b,no.time+1));//放入队列
            update(b);//更新vis数组
        }
 
 
    }
}
 
int main()
{
    int a[8];
    while(scanf("%d",&a[0])!=EOF)
    {
        memset(vis,0,sizeof(vis));
        for(int i=1;i<8;i++)
            scanf("%d",&a[i]);
        if(is_ans(a))cout<<0<<endl;
       else
        cout<<bfs(a)<<endl;
    }
}
accuracy: 1
time_ms: 860
memory_kb: 11396
final_rank: 19

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

using namespace std;

vector<int> a;

int moves[4] = {-1, 1, -4, 4};

map<vector<int>, int> dist;

void pre_calc()
{
    queue<vector<int>> q;
    q.push({0, 1, 2, 3, 4, 5, 6, 7});
    dist[{0, 1, 2, 3, 4, 5, 6, 7}] = 0;
    while (!q.empty())
    {
        auto v = q.front();
        q.pop();
        int pos = find(v.begin(), v.end(), 0) - v.begin();
        for (int i = 0; i < 4; i++)
        {
            int next = pos + moves[i];
            if (next < 0 || next >= 8 || (pos == 3 && next == 4) || (pos == 4 && next == 3))
                continue;
            vector<int> u = v;
            swap(u[pos], u[next]);
            if (dist.find(u) == dist.end())
            {
                dist[u] = dist[v] + 1;
                q.push(u);
            }
        }
    }
}

void solve()
{

    cout << dist[a] << endl;
}

int main()
{
    a = vector<int>(8);
    pre_calc();
    while (cin >> a[0])
    {
        for (int i = 1; i < 8; i++)
            cin >> a[i];
        solve();
        a = vector<int>(8);
    }
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 5868
final_rank: 12

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 main() {
    vector<int> ori(8);
    map<vector<int>, int> mp;
    rep(i, 8) ori[i] = i;
    vector<int> oric = ori;
    do {
        mp[ori] = -1;
    } while (next_permutation(ori.begin(), ori.end()));

    mp[oric] = 0;
    queue<vector<int>> q;
    queue<int> pos;
    int p = 0;
    q.push(oric);
    while (!q.empty()) {
        auto cur = q.front();
        q.pop();
        vector<int> nex = cur;
        rep(i, cur.size()) {
            if (cur[i] == 0) {
                if (i % 4 != 0) { // 左へ
                    swap(nex[i], nex[i - 1]);
                    if (mp[nex] == -1) {
                        q.push(nex);
                        mp[nex] = mp[cur] + 1;
                    }
                    swap(nex[i], nex[i - 1]);
                }
                if (i % 4 != 3) { // 右へ
                    swap(nex[i], nex[i + 1]);
                    if (mp[nex] == -1) {
                        q.push(nex);
                        mp[nex] = mp[cur] + 1;
                    }
                    swap(nex[i], nex[i + 1]);
                }
                if (i >= 4) { // 上へ
                    swap(nex[i], nex[i - 4]);
                    if (mp[nex] == -1) {
                        q.push(nex);
                        mp[nex] = mp[cur] + 1;
                    }
                    swap(nex[i], nex[i - 4]);
                }
                if (i < 4) { // 下へ
                    swap(nex[i], nex[i + 4]);
                    if (mp[nex] == -1) {
                        q.push(nex);
                        mp[nex] = mp[cur] + 1;
                    }
                    swap(nex[i], nex[i + 4]);
                }
            }
        }
    }
    vector<int> a(8);
    while (cin >> a[0]) {  // 8つの数字を順に読み込む
        for (int i = 1; i < 8; i++) {
            cin >> a[i];
        }
        cout << mp[a] << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 8548
final_rank: 16

code_snippet: #include<iostream>
#include<string>
#include<queue>
#include<map>

using namespace std;
map<string, int> mp;
int bh[4] = {-1,1,4,-4};


void bfs()
{
    string s = "01234567";
    queue<string> q;
    mp[s] = 1;
    q.push(s);
    while(!q.empty())
    {
        s = q.front();
        q.pop();
        int i;
        for(i=0;i<8;i++)
        {
            if(s[i]=='0') break;
        }
        for(int j=0;j<4;j++)
        {
            int t = i+bh[j];
            if((t>=0)&&(t<8)&&!((i==3)&&(j==1))&&!((i==4)&&(j==0)))
            {
                string s2 = s;
                s2[t] = s[i];
                s2[i] = s[t];
                if(!mp[s2])
                {
                    mp[s2] = mp[s] + 1;
                    q.push(s2);
                }
            }
        }
    }
}

using namespace std;


int main()
{
    int A[8];
    bfs();
    while(cin >> A[0] >> A[1] >> A[2] >> A[3] >> A[4] >> A[5] >> A[6] >> A[7])
    {
        string s = "";
        s += A[0]+'0';s += A[1]+'0';s += A[2]+'0';s += A[3]+'0';s += A[4]+'0';s += A[5]+'0';s += A[6]+'0';s += A[7]+'0';
        cout << mp[s]-1 << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 5440
final_rank: 10

code_snippet: #include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<string>
using namespace std;
int d[4]={-1,1,-4,4};
map <string,int> mp;
string s;
void bfs()
{
	queue <string> q;
	q.push("01234567");
	mp["01234567"]=0;
	while(!q.empty())
	{
		string now=q.front();
		q.pop();
		int pos=now.find('0');
		for(int i=0;i<4;++i)
		{
			int dpos=pos+d[i];
			if(0<=dpos&&dpos<=7&&(!(pos==4&&i==0))&&(!(pos==3&&i==1)))
			{
				string net=now;
				swap(net[pos],net[dpos]);
				if(mp.find(net)==mp.end())
				{
					q.push(net);
					mp[net]=mp[now]+1;
				}
			}
		}
	}
}
void solve()
{
	printf("%d\n",mp[s]);
}
int main()
{  
   ios::sync_with_stdio(false);
	bfs();
	while(getline(cin,s))
	{
		s.erase(remove(s.begin(),s.end(),' '),s.end());
		solve();
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4928
final_rank: 5

code_snippet: #include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<string>
using namespace std;  
int d[4]={-1,1,-4,4};
map <string,int> mp;
string s;
void bfs()
{
	queue <string> q;
	q.push("01234567"); 
	mp["01234567"]=0;
	while(!q.empty())
	{
		string now=q.front();
		q.pop();
		int pos=now.find('0');
		for(int i=0;i<4;i++)
		{
			int dpos=pos+d[i];
			if(dpos>=0&&dpos<=7&&(!(pos==4&&i==0))&&(!(pos==3&&i==1)))
			{
				string net=now;
				swap(net[pos],net[dpos]);
				if(mp.find(net)==mp.end())
				{
					mp[net]=mp[now]+1;
					q.push(net);
				}
			}
		}
	}
}
void solve()
{
	printf("%d\n",mp[s]);
}
int main()
{
	ios::sync_with_stdio(false);
	bfs();
	while(getline(cin,s))	
	{
		s.erase(remove(s.begin(),s.end(),' '),s.end());
		solve();
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 5092
final_rank: 9

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

int a[8];
map<int, int> table;
queue<int> que;

int main() {
    table[1234567] = 0;
    que.push(1234567);
    while (!que.empty()) {
        int n = que.front(); que.pop();
        int a[4][2];
        int tmp = n;
        int idx, idy;
        for (int i = 0; i < 8; i++) {
            int x = i % 4, y = i / 4;
            a[x][y] = tmp % 10;
            tmp /= 10;
            if (a[x][y] == 0)
                idx = x, idy = y;
        }
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
        for (int i = 0; i < 4; i++) {
            int ndx = idx + dx[i], ndy = idy + dy[i];
            if (ndx >= 0 && ndx < 4 && ndy >= 0 && ndy < 2) {
                swap(a[idx][idy], a[ndx][ndy]);
                int m = 0;
                for (int x = 0; x < 4; x++) {
                    for (int y = 0; y < 2; y++) {
                        m += a[x][y] * int(pow(10, x + 4 * y));
                    }
                }
                if (table.count(m) == 0) {
                    table[m] = table.at(n) + 1;
                    que.push(m);
                }
                swap(a[idx][idy], a[ndx][ndy]);
            }
        }
    }
    int b[8];
    while (cin >> b[0]) {
        for (int i = 1; i < 8; i++) {
            cin >> b[i];
        }
        int n = 0;
        for (int i = 0; i < 8; i++) {
            n += b[7 - i] * int(pow(10, i));
        }
        cout << table.at(n) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 4228
final_rank: 2

code_snippet: #include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
#define INF 1e8
map<string, int> res;
const int dx[4] = {4, -4, 1, -1};
bool valid(int x)
{
    return x >= 0 && x < 8;
}

void bfs()
{
    res["01234567"] = 0;
    queue<string> q;
    q.push("01234567");
    while (!q.empty())
    {
        string s = q.front();
        q.pop();
        int x = s.find('0',0);

        for (int i = 0; i < 4; i++)
        {
            int tx = x + dx[i];
            string t = s;
            if (valid(tx) && !(x == 3 && tx == 4) && !(x == 4 && tx == 3))
            {
                swap(t[x], t[tx]);
                if (res.find(t) == res.end())
                {
                    res[t] = res[s] + 1;
                    q.push(t);
                }
            }
        }
    }
}
void solve()
{
    bfs();

    string s;
    while (getline(cin, s))
    {
        s.erase(remove(s.begin(), s.end(), ' '), s.end());
        cout << res[s] << "\n";
    }
}
int main()
{
    ios::sync_with_stdio(false);
    std::cin.tie(0);
    std::cout.tie(0);

    int T = 1;
    // cin >> T;
    while (T--)
    {
        solve();
    }
}
accuracy: 1
time_ms: 10
memory_kb: 4752
final_rank: 3

code_snippet: #include<string>
#include<map>
#include<bits/stdc++.h>
#include<queue>
#include<iostream>
using namespace std;
string s={"01234567"};
int ch[4]={1,-1,4,-4};
map<string,int>mp;
void bfs(){
    queue<string> q;
    q.push(s);
    while(!q.empty()){
        string p=q.front();
        q.pop();
        int pos=p.find("0");
        for(int i=0;i<4;i++){
            int tpos=pos+ch[i];
            if(tpos>=0&&tpos<=7&&!(pos==3&&i==0)&&!(pos==4&&i==1)){
                string c=p;
                swap(c[pos],c[tpos]);
                if(mp[c]==0&&c!="01234567"){
                    mp[c]=mp[p]+1;
                    q.push(c);
                }
            }
        }
    }
}
int main(){
	bfs();
	while(getline(cin,s)){
		s.erase(remove(s.begin(),s.end(),' '),s.end());
		printf("%d\n",mp[s]);
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 5088
final_rank: 8

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

int main() {
  int p, d, c {};
  vector<int> v {0, 1, 2, 3, 4, 5, 6, 7};
  map<vector<int>, int> mp;
  mp[v] = 0;
  queue<vector<int>> q;
  q.push(v);
  while (!q.empty()) {
    vector<int> a {q.front()};
    d = mp[a];
    q.pop();
    for (int i = 0; i < 8; ++i) {
      if(a[i] == 0) p = i;
    }
    if (p < 4) {
      swap(a[p], a[p+4]);
      if (!mp.count(a)) {
        mp[a] = d + 1;
        q.push(a);
      }
      swap(a[p], a[p+4]);
    }
    else {
      swap(a[p], a[p-4]);
      if (!mp.count(a)) {
        mp[a] = d + 1;
        q.push(a);
      }
      swap(a[p], a[p-4]);
    }
    if (p % 4) {
      swap(a[p], a[p-1]);
      if (!mp.count(a)) {
        mp[a] = d + 1;
        q.push(a);
      }
      swap(a[p], a[p-1]);
    }
    if (p % 4 != 3) {
      swap(a[p], a[p+1]);
      if (!mp.count(a)) {
        mp[a] = d + 1;
        q.push(a);
      }
    }
  }
  vector<int> u(8);
  while (cin >> u[0]) {
    for (int i = 1; i < 8; ++i) {
      cin >> u[i];
    }
    cout << mp[u] << '\n';
  }
  // for (auto& [a, b]: mp) {
  //   cout << b << '\n';
  //   for (int i = 0; i < 8; ++i) cout << a[i] << ' ';
  //   cout << '\n';
  // }
}
accuracy: 1
time_ms: 10
memory_kb: 5740
final_rank: 11

code_snippet: #include <algorithm>
#include <string>
#include <vector>
#include <iostream>
#include <queue>
#include <map>
using namespace std;
typedef pair<vector<vector<int>>, pair<int, int>> P;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

map<vector<vector<int>>, int> costs;
void bfs(P start){
  costs[start.first] = 0;
  queue<P> que;
  que.push(start);

  while(que.size() > 0){
    P now = que.front();
    que.pop();
    for(int i = 0; i < 4; i++){
        if(0 <= now.second.first + dx[i] && now.second.first + dx[i] < 2 && 0 <= now.second.second + dy[i] && now.second.second + dy[i] < 4){
            P sample = now;
            swap(sample.first[now.second.first + dx[i]][now.second.second + dy[i]], sample.first[now.second.first][now.second.second]);
            if(!costs.count(sample.first)){
                costs[sample.first] = costs[now.first] + 1;
                sample.second.first += dx[i];
                sample.second.second += dy[i];
                que.push(sample);
            } 
        }
    }
  }
}

int main(){
    vector<vector<int>> ans{{0, 1, 2, 3}, {4, 5, 6, 7}};
    P start;
    start.first = ans;
    start.second.first = 0;
    start.second.second = 0;
    bfs(start);
    vector<vector<int>> vec(2, vector<int>(4));
    while(cin >> vec[0][0] >> vec[0][1] >> vec[0][2] >> vec[0][3] >> vec[1][0] >> vec[1][1] >> vec[1][2] >> vec[1][3]){
        //print the answer
        cout << costs[vec] << endl;
    }
}
accuracy: 1
time_ms: 30
memory_kb: 7556
final_rank: 15