You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a $2 \times (2k + 1)$ rectangular grid. The alien has $4k + 1$ distinct organs, numbered $1$ to $4k + 1$.

In healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for $k = 4$: [Image] 

Here, the E represents empty space. 

In general, the first row contains organs $1$ to $2k + 1$ (in that order from left to right), and the second row contains organs $2k + 2$ to $4k + 1$ (in that order from left to right) and then empty space right after. 

Your patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things:  You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space;  You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) only if the empty space is on the leftmost column, rightmost column or in the centermost column. Again, you do this by sliding the organ in question to the empty space. 

Your job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all $4k + 1$ internal organs of your patient in the correct cells. If it is impossible to do so, you must say so.


-----Input-----

The first line of input contains a single integer $t$ ($1 \le t \le 4$) denoting the number of test cases. The next lines contain descriptions of the test cases.

Each test case consists of three lines. The first line contains a single integer $k$ ($1 \le k \le 15$) which determines the size of the grid. Then two lines follow. Each of them contains $2k + 1$ space-separated integers or the letter E. They describe the first and second rows of organs, respectively. It is guaranteed that all $4k + 1$ organs are present and there is exactly one E.


-----Output-----

For each test case, first, print a single line containing either:  SURGERY COMPLETE if it is possible to place back all internal organs in the correct locations;  SURGERY FAILED if it is impossible. 

If it is impossible, then this is the only line of output for the test case. However, if it is possible, output a few more lines describing the sequence of moves to place the organs in the correct locations. 

The sequence of moves will be a (possibly empty) string of letters u, d, l or r, representing sliding the organ that's directly above, below, to the left or to the right of the empty space, respectively, into the empty space. Print the sequence of moves in the following line, as such a string. 

For convenience, you may use shortcuts to reduce the size of your output. You may use uppercase letters as shortcuts for sequences of moves. For example, you could choose T to represent the string lddrr. These shortcuts may also include other shortcuts on their own! For example, you could choose E to represent TruT, etc.

You may use any number of uppercase letters (including none) as shortcuts. The only requirements are the following:  The total length of all strings in your output for a single case is at most $10^4$;  There must be no cycles involving the shortcuts that are reachable from the main sequence;  The resulting sequence of moves is finite, after expanding all shortcuts. Note that the final sequence of moves (after expanding) may be much longer than $10^4$; the only requirement is that it's finite. 

As an example, if T = lddrr, E = TruT and R = rrr, then TurTlER expands to:  TurTlER  lddrrurTlER  lddrrurlddrrlER  lddrrurlddrrlTruTR  lddrrurlddrrllddrrruTR  lddrrurlddrrllddrrrulddrrR  lddrrurlddrrllddrrrulddrrrrr 

To use shortcuts, print each one of them in a single line as the uppercase letter, then space, and then the string that this shortcut represents. They may be printed in any order. At the end of all of those, print a single line containing DONE. 

Note: You still need to print DONE even if you don't plan on using shortcuts.

Your sequence does not need to be the shortest. Any valid sequence of moves (satisfying the requirements above) will be accepted.


-----Example-----
Input
2
3
1 2 3 5 6 E 7
8 9 10 4 11 12 13
11
34 45 6 22 16 43 38 44 5 4 41 14 7 29 28 19 9 18 42 8 17 33 1
E 15 40 36 31 24 10 2 21 11 32 23 30 27 35 25 13 12 39 37 26 20 3

Output
SURGERY COMPLETE
IR
R SrS
S rr
I lldll
DONE
SURGERY FAILED



-----Note-----

There are three shortcuts defined in the first sample output:  R = SrS  S = rr  I = lldll 

The sequence of moves is IR and it expands to:  IR  lldllR  lldllSrS  lldllrrrS  lldllrrrrr

Source: codeforces | Difficulty: VERY_HARD
Tags: Combinatorics

Mathematics

Constructive algorithms


Solutions:
def solve(k, grid):
	seek = (*list(range(2 * k + 2)), *list(range(4 * k + 1, 2 * k + 1, -1)))
	flat = [seek[v] for v in grid[0] + grid[1][::-1] if v]
	m = {'L': 'l' * 2 * k + 'u' + 'r' * 2 * k + 'd', 'R': 'u' + 'l' * 2 * k + 'd' + 'r' * 2 * k, 'C': 'l' * k + 'u' + 'r' * k + 'd', 'D': 'CC' + 'R' * (2 * k + 1) + 'CC' + 'R' * (2 * k + 2), 'F': 'R' * (k - 1) + 'DD' + 'R' * (2 * k + 1) + 'D' + 'L' * 2 * k + 'DD' + 'L' * k, 'G': 'FF'}
	[(i, j)] = [(i, j) for i in range(2) for j in range(2 * k + 1) if grid[i][j] == 0]
	st = 'r' * (2 * k - j) + 'd' * (1 - i)
	for v in range(2, 4 * k + 2):
		ct = flat.index(v)
		if ct >= 2:
			st += 'L' * (ct - 2) + 'GR' * (ct - 2) + 'G'
			flat = flat[ct - 1:ct + 1] + flat[:ct - 1] + flat[ct + 1:]
		if ct >= 1:
			st += 'G'
			flat = flat[1:3] + flat[:1] + flat[3:]
		st += 'L'
		flat = flat[1:] + flat[:1]
	if flat[0] == 1:
		return (st, m)

def main():

	def get_line():
		return [0 if x == 'E' else int(x) for x in input().split()]
	for cas in range(int(input())):
		res = solve(int(input()), [get_line() for i in range(2)])
		if res is None:
			print('SURGERY FAILED')
		else:
			print('SURGERY COMPLETE')
			(st, m) = res
			print(st)
			for shortcut in list(m.items()):
				print(*shortcut)
			print('DONE')
main()


def solve(kk, grid):
	sk = (*range(kk * 2 + 2), *range(4 * kk + 1, 2 * kk + 1, -1))
	flat = [sk[v] for v in grid[0] + grid[1][::-1] if v]
	dir = {'L': 'l' * 2 * kk + 'u' + 'r' * 2 * kk + 'd', 'R': 'u' + 'l' * 2 * kk + 'd' + 'r' * 2 * kk, 'C': 'l' * kk + 'u' + 'r' * kk + 'd', 'D': 'CC' + 'R' * (2 * kk + 1) + 'CC' + 'R' * (2 * kk + 2), 'F': 'R' * (kk - 1) + 'DD' + 'R' * (2 * kk + 1) + 'D' + 'L' * 2 * kk + 'DD' + 'L' * kk, 'G': 'FF'}
	[(i, j)] = [(i, j) for i in range(2) for j in range(2 * kk + 1) if grid[i][j] == 0]
	st = 'r' * (2 * kk - j) + 'd' * (1 - i)
	for i in range(2, 4 * kk + 2):
		tt = flat.index(i)
		if tt >= 2:
			st += 'L' * (tt - 2) + 'GR' * (tt - 2) + 'G'
			flat = flat[tt - 1:tt + 1] + flat[:tt - 1] + flat[tt + 1:]
		if tt >= 1:
			st += 'G'
			flat = flat[1:3] + flat[:1] + flat[3:]
		st += 'L'
		flat = flat[1:] + flat[:1]
	if flat[0] == 1:
		return (st, dir)

def getline():
	return [0 if x == 'E' else int(x) for x in input().split()]
for case in range(int(input())):
	ret = solve(int(input()), [getline() for i in range(2)])
	if ret is None:
		print('SURGERY FAILED')
	else:
		print('SURGERY COMPLETE')
		(st, vv) = ret
		print(st)
		for shortcut in vv.items():
			print(*shortcut)
		print('DONE')


import sys
OP_CW1 = 'A'
OP_CW4 = 'B'
OP_CW16 = 'C'
OP_CCW = 'E'
OP_L = 'U'
OP_INV_L = 'V'
OP_R = 'W'
OP_INV_R = 'X'
OP_S = 'S'
OP_MOVE_LL1 = 'O'
OP_MOVE_LL4 = 'P'
OP_MOVE_LL16 = 'Q'
OP_MOVE_L_THROW = 'R'

def GetK(board):
	return len(board) // 4

def Slot(board, slotval=-1):
	return board.index(slotval)

def KS(board, slotval=-1):
	return (GetK(board), Slot(board, slotval))

def Width(K):
	return K * 2 + 1

def PrintPermumation(head, board, slotval=None):
	K = GetK(board)
	W = Width(K)
	if slotval is None:
		slotval = K
	slot = Slot(board, slotval)
	print(head, '===', file=sys.stderr)
	tostr = lambda x: 'EE' if x == slotval else '%2d' % x
	for row in [board[:W], board[W:]]:
		print(' '.join((tostr(x) for x in row)), file=sys.stderr)

def ApplyOps(board, seq, ops=None, slotval=-1):
	(K, slot) = KS(board, slotval)
	W = Width(K)
	for c in seq:
		if c == 'l':
			assert slot % W > 0, slot
			s1 = slot - 1
		elif c == 'r':
			assert slot % W + 1 < W, slot
			s1 = slot + 1
		elif c == 'd':
			assert slot % W in [0, K, K * 2], slot
			assert slot // W == 0
			s1 = slot + W
		elif c == 'u':
			assert slot % W in [0, K, K * 2], slot
			assert slot // W == 1
			s1 = slot - W
		else:
			s1 = None
		if s1 is not None:
			(board[s1], board[slot]) = (board[slot], board[s1])
		else:
			P = ops[c]
			tmp = board[:]
			for i in range(len(board)):
				board[i] = tmp[P[i]]
		slot = Slot(board, slotval)

def LoopedView(board):
	(K, slot) = KS(board)
	W = Width(slot)
	assert slot == K

	def translate(x):
		if x == -1:
			return x
		if x <= W:
			return x - 1
		return 3 * W - 1 - x
	r = []
	for rng in [range(slot + 1, W), reversed(range(W, W * 2)), range(0, slot)]:
		for i in rng:
			r.append(translate(board[i]))
	return r

def Mod(x, m):
	x %= m
	if x < 0:
		x += m
	return x

def CanonicalizeView(view):
	i = view.index(0)
	view[:] = view[i:] + view[:i]

def ToPermutation(K, ops, seq):
	board = list(range(K * 4 + 2))
	ApplyOps(board, seq, ops, slotval=K)
	return board

def InitOps(K, debug=False):
	W = Width(K)
	ops = {}
	ops_codes = {}

	def ToP(seq):
		return ToPermutation(K, ops, seq)

	def Assign(rep, seq):
		ops[rep] = ToP(seq)
		ops_codes[rep] = seq
	Assign(OP_CW1, 'l' * K + 'd' + 'r' * (K * 2) + 'u' + 'l' * K)
	if debug:
		PrintPermumation('CW1', ops[OP_CW1])
	Assign(OP_CW4, OP_CW1 * 4)
	if debug:
		PrintPermumation('CW4', ops[OP_CW4])
	Assign(OP_CW16, OP_CW4 * 4)
	Assign(OP_CCW, OP_CW1 * (W * 2 - 2))
	if debug:
		PrintPermumation('CCW', ops[OP_CCW])
	Assign(OP_L, 'l' * K + 'd' + 'r' * K + 'u')
	if debug:
		PrintPermumation('L', ops[OP_L])
	Assign(OP_INV_L, OP_L * (K * 2))
	if debug:
		PrintPermumation('INV_L', ops[OP_INV_L])
	Assign(OP_R, 'r' * K + 'd' + 'l' * K + 'u')
	if debug:
		PrintPermumation('R', ops[OP_R])
	Assign(OP_INV_R, OP_R * (K * 2))
	if debug:
		PrintPermumation('INV_R', ops[OP_INV_R])
	Assign(OP_S, OP_INV_R + OP_INV_L + OP_R + OP_L)
	if debug:
		PrintPermumation('S', ops[OP_S])
	Assign(OP_MOVE_LL1, OP_CW1 + OP_S + OP_CW1)
	Assign(OP_MOVE_LL4, OP_MOVE_LL1 * 4)
	Assign(OP_MOVE_LL16, OP_MOVE_LL4 * 4)
	Assign(OP_MOVE_L_THROW, OP_S * 2 + OP_CW1)
	if debug:
		PrintPermumation('MOVE_LL', ops[OP_MOVE_LL1])
		PrintPermumation('MOVE_L_THROW', ops[OP_MOVE_L_THROW])
	return (ops, ops_codes)

def Solve(board, debug=False):
	ans = []
	(K, slot) = KS(board)
	W = Width(K)
	if slot % W < K:
		t = 'r' * (K - slot % W)
	else:
		t = 'l' * (slot % W - K)
	if slot // W == 1:
		t = t + 'u'
	ans.append(t)
	ApplyOps(board, t)
	slot = Slot(board)
	assert slot == K
	(ops, ops_codes) = InitOps(K)

	def ApplyMultipleOp(num, items):
		for (k, op) in reversed(items):
			while num >= k:
				num -= k
				ApplyOps(board, op, ops)
				ans.append(op)
	for k in range(1, W * 2 - 1):
		view = LoopedView(board)
		if debug:
			print('=' * 20, k, '\n', view, file=sys.stderr)
		num_cw = Mod(+(K * 2 - view.index(k)), len(view))
		CanonicalizeView(view)
		num_move = view.index(k) - k
		if debug:
			print(num_cw, num_move, file=sys.stderr)
		ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)])
		if debug:
			PrintPermumation('t', board, slotval=-1)
		ApplyMultipleOp(num_move // 2, [(1, OP_MOVE_LL1), (4, OP_MOVE_LL4), (16, OP_MOVE_LL16)])
		if debug:
			PrintPermumation('tt', board, slotval=-1)
		if num_move % 2 > 0:
			if k == W * 2 - 2:
				return False
			ApplyOps(board, OP_MOVE_L_THROW, ops)
			ans.append(OP_MOVE_L_THROW)
	view = LoopedView(board)
	num_cw = Mod(K * 3 + 1 - view.index(0), len(view))
	ApplyMultipleOp(num_cw, [(1, OP_CW1), (4, OP_CW4), (16, OP_CW16)])
	if debug:
		PrintPermumation('ttt', board, slotval=-1)
	f = 'r' * K + 'd'
	ApplyOps(board, f)
	ans.append(f)
	if debug:
		PrintPermumation('ttt', board, slotval=-1)
	print('SURGERY COMPLETE')
	print(''.join(ans))
	for (k, v) in ops_codes.items():
		print(k, v)
	print('DONE')
	return True
for _ in range(int(sys.stdin.readline())):
	sys.stdin.readline()
	tr = lambda s: -1 if s == 'E' else int(s)
	row1 = list(map(tr, sys.stdin.readline().split()))
	row2 = list(map(tr, sys.stdin.readline().split()))
	if not Solve(row1 + row2):
		print('SURGERY FAILED')