AcWing 180. 排书 IDA*算法应用
原题链接
中等
作者:
皓首不倦
,
2020-08-05 22:06:17
,
所有人可见
,
阅读 436
T = int(input())
for _ in range(T):
n = int(input())
arr = list( map(int, input().split()) )
def dfs(cur_arr, step, max_step):
#print(cur_arr, step, max_step)
if step == max_step:
return tuple(cur_arr) == tuple([i for i in range(1, n+1)])
for i in range(n):
if i >= 1 and cur_arr[i] == cur_arr[i-1] + 1:
continue
for j in range(i, n):
if j < n-1 and cur_arr[j] == cur_arr[j+1]-1:
continue
for length in range(1, n-j):
if cur_arr[i] < cur_arr[j+length]:
continue
new_arr = cur_arr[:i] + cur_arr[j+1:j+1+length] + cur_arr[i:j+1] + cur_arr[j+1+length:]
cnt = 0
for k in range(1, n):
if new_arr[k] != new_arr[k-1] + 1:
cnt += 1
if ((cnt+2) // 3) + step <= max_step:
# 每次移动最多会造成三个字符的后继变化,最少还需要要(cnt+2) // 3次移动才可能到最终状态
if dfs(new_arr, step+1, max_step):
return True
return False
flag = False
for depth in range(0, 5):
if dfs(arr, 0, depth):
flag = True
print(depth)
break
if not flag:
print('5 or more')