#include <iostream>
#include <math.h>
#include <queue>
#include <map>
#include <string>
using namespace std;
int bfs(int p,int q) {
	typedef pair <int, int>P;
	map<int, int> d;
	queue<P> que;
	que.push(P(p,q));
	d[p] = 0;
	int ten4=1;
	for (int i = 0; i < 4; i++) {
		ten4 *= 10;
	}
	while (que.size()) {
		P p = que.front(); que.pop();
		if (p.first == 81234567)  break; 
		int a = 1; int a1;
		if (p.second!=7&&p.second!=3) {
			for (int i = 0; i <= p.second; i++) {
				a *= 10;
			}
			a1 = p.first + (8 - (p.first / a) % 10)*(a - a / 10);
			if (d[a1] == 0) {
				que.push(P(a1, p.second + 1));
				d[a1] = d[p.first] + 1;
			}
		}
		int b = 1; int b1;
		if (p.second!=0&&p.second != 4) {
			for (int i = 0; i < p.second-1; i++) {
				b *= 10;
			}
			b1 = p.first + (8 - (p.first / b) % 10)*(-10*b + b);
			if (d[b1] == 0) {
				que.push(P(b1, p.second - 1));
				d[b1] = d[p.first] + 1;
			}
		}
		int c = 1; int c1;
		if (p.second<4) {
			for (int i = 0; i < p.second; i++) {
				c *= 10;
			}
			c1 = p.first + (8 - (p.first / (c*ten4)) % 10)*(c*ten4-c);
			if (d[c1] == 0) {
				que.push(P(c1, p.second + 4));
				d[c1] = d[p.first] + 1;
			}
		}
		int e = 1; int e1;
		if (p.second > 3) {
			for (int i = 0; i < p.second; i++) {
				e *= 10;
			}
			e1 = p.first - (8 - (p.first / (e/ten4)) % 10)*(e - e/ten4);
			if (d[e1] == 0) {
				que.push(P(e1, p.second - 4));
				d[e1] = d[p.first] + 1;
			}
		}
	}
	return d[81234567];
}
int main() {
	int t = 1, x = 0, y = 0, z = 0; int a[8]; bool flag = true;
	while (flag) {
		x = 0;
		for (int i = 0; i < 8; i++) {
			cin >> a[i];
			if (a[i] == 0) { a[i] = 8; y = 7 - i; }
			for (int j = 0; j < 7 - i; j++) {
				t *= 10;
			}
			x += a[i] * t; t = 1; 
		}
		if (z == x) {
        break;
		}
		else {
			z = x;
		}
		int res = bfs(x, y);
		cout << res << endl;
	}
}