#include <algorithm>
#include <bitset>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <utility>
using namespace std;

#define ABS(a) (((a) >= 0) ? (a) : -(a))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define FOR(i, a, b) for (int i = a; i < b; ++i)
#define RFOR(i, a, b) for (int i = a; i > b; --i)
#define REP(i, n) for (int i = 0; i < n; ++i)
#define int long long

typedef long long ll;
typedef pair<int, int> Pair;

const int kMaxH = 1000;
const int kMaxW = 1000;
const int kInf = 1000000000;

int ans = 0;

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

typedef struct {
  int f[2][4];
  int zx, zy;
  int cnt;
} Field;

string Pattern(Field f) {
  string p;
  REP(i, 2) { REP(j, 4) { p.push_back('0'+f.f[i][j]); } }
  return p;
}

bool IsCompleted(Field f) {
  int z = 0;
  REP(i, 2) { REP(j, 4) { if (f.f[i][j] != z++) { return false; } } }
  return true;
}

int Bfs(Field f0) {
  set<string> pattern;

  queue<Field> que;
  pattern.insert(Pattern(f0));
  que.push(f0);

  while (que.size()) {
    Field f = que.front(); que.pop();
    // cout << f.cnt << endl;
    if (IsCompleted(f)) { return f.cnt; }
    REP(i, 4) {
      int nx = f.zx+dx[i]; int ny = f.zy+dy[i];
      if (0 <= nx && nx < 2 && 0 <= ny && ny < 4) {
        Field nf;
        REP(i, 2) { REP(j, 4) { nf.f[i][j] = f.f[i][j]; } }
        nf.zx = f.zx; nf.zy = f.zy;
        nf.cnt = f.cnt;

        int tmp = nf.f[nx][ny];
        nf.f[nx][ny] = nf.f[nf.zx][nf.zy];
        nf.f[nf.zx][nf.zy] = tmp;
        nf.zx = nx; nf.zy = ny;
        ++nf.cnt;

        auto r = pattern.insert(Pattern(nf));
        if (r.second) { que.push(nf); }
      }
    }
  }

  return -1;
}

signed main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int N = 500;
  while (N--) {
    Field f0;
    REP(i, 2) {
      REP(j, 4) {
        cin >> f0.f[i][j];
        if (i == 0 && j == 0 && cin.fail()) { goto r; }
      }
    }
    REP(i, 2) { REP(j, 4) { if (f0.f[i][j] == 0) { f0.zx = i; f0.zy = j; } } }
    f0.cnt = 0;
    ans = Bfs(f0);
    cout << ans << endl;
  }
r:
  return 0;
}

