1 2 3 5 4 6 7 8

2
5
2 1 5 3 4
5
2 5 1 3 4

3
Too chaotic

1 2 3 4 5

5和4交換：

1 2 3 5 4

5和3交換：

1 2 5 3 4

2和1交換：

2 1 5 3 4

#### 參考答案

```import java.util.Scanner;

public class Solution {

public static void main(final String[] args) {
final Scanner sc = new Scanner(System.in);

int T = Integer.parseInt(sc.nextLine());
while (T-- > 0) {
final int n = sc.nextInt();
final Person[] a = new Person[n];
for (int i = 0; i < n; ++i) {
a[i] = new Person(sc.nextInt());
}

final int n_dec = n - 1;
int counter = 0;
RECOVER:
for (int i = 0; i < n_dec; ++i) {
final int d = a[i].firstPosition - i;
if (d > 3) {
counter = -1;
break;
} else if (d != 1) {
for (int j = n_dec - 1; j >= i; --j) {
if (a[j].firstPosition > a[j + 1].firstPosition) {
if (!a[j].bribes()) {
counter = -1;
break RECOVER;
}
final Person temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
++counter;
}
}
}
}
System.out.println(counter > -1 ? counter : "Too chaotic");
}
}
}

class Person {

final int firstPosition;
private int bribesChance = 2;

Person(final int finalPosition) {
this.firstPosition = finalPosition;
}

boolean bribes() {
if (bribesChance == 0) {
return false;
}
--bribesChance;
return true;
}

@Override
public String toString() {
return String.valueOf(firstPosition);
}
}```