#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
#define pr(x) cout<<#x<<" "<<x;
#define pl(x) cout<<#x<<" "<<x<<endl;
#include<math.h>
#include<algorithm>
#include<set>
using namespace std;
int maze[2][4];
int dx[] = {1,-1,0,0};
int dy[] = {0,0,-1,1};

struct p{
    int x,y,step;
    int num;
};
queue <p> que;
set <int> s;
bool judge(p cp){
    if(cp.num==1234567){return true;}
    else{return false;}
}
void jiexi(p cp){
    int a = cp.num;
    for(int i= 1;i>=0;i--){
            for(int j=3;j>=0;j--){
                maze[i][j]=a%10;
                a/=10;
            }
        }

}
void bfs(){
    while(que.size()){
        p cp;
        cp = que.front();
        que.pop();
        if(judge(cp)){printf("%d\n",cp.step);break;}
        for(int i = 0;i<4;i++){
            jiexi(cp);
            int nx = cp.x + dx[i];
            int ny = cp.y + dy[i];
            if(nx>=0&&nx<2&&ny>=0&&ny<4){
                int temp = maze[cp.x][cp.y];
                maze[cp.x][cp.y] = maze[nx][ny];
                maze[nx][ny] = temp;
                p np;
                np.x =nx;
                np.y = ny;
                np.step = cp.step+1;
                np.num=0;
                for(int i= 0;i<2;i++){
                    for(int j=0;j<4;j++){
                        np.num =np.num*10+ maze[i][j];
                    }
                }
                if(!s.count(np.num)){
                   que.push(np);
                   s.insert(np.num);
                }

            }
        }
    }
    while(que.size()){que.pop();}
    s.clear();
}

int main(){
    while(scanf("%d %d %d %d %d %d %d %d",&maze[0][0],&maze[0][1],&maze[0][2],&maze[0][3],&maze[1][0],&maze[1][1],&maze[1][2],&maze[1][3])!=EOF){
        p cp;
        cp.num=0;
        for(int i = 0;i<2;i++){
            for(int j = 0;j<4;j++){
                cp.num =cp.num*10+ maze[i][j];
                if(maze[i][j] == 0){
                    cp.x = i;
                    cp.y = j;
                    cp.step = 0;
                }
            }
        }

        que.push(cp);
        s.insert(cp.num);
        bfs();
    }



}