I - Swap Puzzle Editorial /

Time Limit: 2 sec / Memory Limit: 1024 MiB

問題文

2 マス、横 4 マスのグリッドがあります。
各マスには数が書きこまれていて、上から i 行目、左から j 列目には (i-1) \times 4 + j が書きこまれています。
あなたは次の 2 種類の操作を好きな順番で何回でも行うことが出来ます。

  • 縦に隣接している 2 つのマスを選び、書かれている数を入れ替える。
  • 横に隣接している 2 つのマスを選び、書かれている数を入れ替える。

A_{i,j} (1 \leq i \leq 2, 1 \leq j \leq 4) が入力で与えられます。
グリッドが次の条件を満たした状態になるには最小で何回の操作が必要ですか?

  • 全ての i, j に対して、上から i 行目、左から j 列目のマスに A_{i,j} が書きこまれている。

制約

  • 1 \leq A_{i,j} \leq 8
  • A_{i,j} は全て異なる
  • 入力される値は全て整数

入力

入力は以下の形式で標準入力から与えられる。

A_{1,1} A_{1,2} A_{1,3} A_{1,4}
A_{2,1} A_{2,2} A_{2,3} A_{2,4}

出力

問題文の条件を満たすために必要な最小の操作回数を出力せよ。


入力例 1

5 2 4 3
1 6 7 8

出力例 1

2

例えば以下の手順で 2 回の操作を行うことで問題文の条件を満たすことができます。

  • 上から 1 行目、左から 1 列目に書かれた数と、上から 2 行目、左から 1 列目に書かれた数を入れ替える。
  • 上から 1 行目、左から 3 列目に書かれた数と、上から 1 行目、左から 4 列目に書かれた数を入れ替える。

1 回以下の操作で問題文の条件を満たすことはできないので、答えは 2 です。


入力例 2

1 2 3 4
5 6 7 8

出力例 2

0

入力例 3

7 4 5 8
2 6 3 1

出力例 3

8

Problem Statement

There is a grid with two horizontal rows and four vertical columns.
Each cell has a number written on it; the cell in the i-th row from the top and j-th column from the left has (i-1) \times 4 + j written on it.
You may perform the following two kinds of operations any number of times in any order.

  • Choose two horizontally adjacent cells, and swap the numbers written on them.
  • Choose two vertically adjacent cells, and swap the numbers written on them.

You are given A_{i,j} (1 \leq i \leq 2, 1 \leq j \leq 4) as the input.
At least how many operations are required to make the grid satisfy the following condition?

  • For all i and j, A_{i,j} is written on the cell in the i-th row from the top and j-th column from the left.

Constraints

  • 1 \leq A_{i,j} \leq 8
  • A_{i,j} are distinct.
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

A_{1,1} A_{1,2} A_{1,3} A_{1,4}
A_{2,1} A_{2,2} A_{2,3} A_{2,4}

Output

Print the minimum number of operations required to satisfy the condition in the problem statement.


Sample Input 1

5 2 4 3
1 6 7 8

Sample Output 1

2

For example, the condition in the problem statement can be satisfied with two operations as follows:

  • Swap the number written on the cell in the 1-st row from the top and 1-st column from the left, and the number written on the cell in the 2-nd row from the top and 1-st column from the left.
  • Swap the number written on the cell in the 1-st row from the top and 3-rd column from the left, and the number written on the cell in the 1-st row from the top and 4-th column from the left.

The condition cannot be satisfied with one operation or less, so 2 is the answer.


Sample Input 2

1 2 3 4
5 6 7 8

Sample Output 2

0

Sample Input 3

7 4 5 8
2 6 3 1

Sample Output 3

8