### Magic 5-gon ring题号：68 难度： 25 中英对照

Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding to nine.

Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), each solution can be described uniquely. For example, the above solution can be described by the set: 4,3,2; 6,2,1; 5,1,3.

It is possible to complete the ring with four different totals: 9, 10, 11, and 12. There are eight solutions in total.

 Total Solution Set 9 4,2,3; 5,3,1; 6,1,2 9 4,3,2; 6,2,1; 5,1,3 10 2,3,5; 4,5,1; 6,1,3 10 2,5,3; 6,3,1; 4,1,5 11 1,4,6; 3,6,2; 5,2,4 11 1,6,4; 5,4,2; 3,2,6 12 1,5,6; 2,6,4; 3,4,5 12 1,6,5; 3,5,4; 2,4,6

By concatenating each group it is possible to form 9-digit strings; the maximum string for a 3-gon ring is 432621513.

Using the numbers 1 to 10, and depending on arrangements, it is possible to form 16- and 17-digit strings. What is the maximum 16-digit string for a "magic" 5-gon ring?

### Code

public final class p68  {

public static void main(String[] args) {
long start = System.nanoTime();
long result = run();
long end = System.nanoTime();
System.out.println( result );
System.out.println (( end - start )/1000000 +"ms");
}

public static long run() {
int[] state = new int[10];
for (int i = 0; i < state.length; i++)
state[i] = i + 1;

String max = null;
do {
int sum = state[0] + state[5] + state[6];
if (   state[1] + state[6] + state[7] != sum
|| state[2] + state[7] + state[8] != sum
|| state[3] + state[8] + state[9] != sum
|| state[4] + state[9] + state[5] != sum)
continue;

int minOuterIndex = -1;
int minOuter = Integer.MAX_VALUE;
for (int i = 0; i < 5; i++) {
if (state[i] < minOuter) {
minOuterIndex = i;
minOuter = state[i];
}
}

String s = "";
for (int i = 0; i < 5; i++)
s += "" + state[(minOuterIndex + i) % 5] + state[(minOuterIndex + i) % 5 + 5] + state[(minOuterIndex + i + 1) % 5 + 5];
if (s.length() == 16 && (max == null || s.compareTo(max) > 0))
max = s;
} while (nextPermutation(state));

if (max == null)
throw new AssertionError();
return Long.valueOf(max);
}
//取下一个排序，直到所有的数字是按降序排列的为止。
public static boolean nextPermutation(int[] a) {
int n = a.length, i, j;
for (i = n - 2; ; i--) {
if (i < 0)
return false;
if (a[i] < a[i + 1])
break;
}
for (j = 1; i + j < n - j; j++) {
int tp = a[i + j];
a[i + j] = a[n - j];
a[n - j] = tp;
}
for (j = i + 1; a[j] <= a[i]; j++);
int tp = a[i];
a[i] = a[j];
a[j] = tp;
return true;
}

}
6531031914842725
52ms