- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 142 lines of Python from the credited upstream file ccc12s4.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 55n = 056visited = []57 58class Node:59 def __init__(self, m, l):60 self.m = m61 self.level = l62 63def done (move):64 global n65 i = 066 while i < n and move[i] == str(i+1):67 i = i + 168 return i == n 69 70def movetoBaseN (move):71 global n72 basen = 073 for i in range(n):74 for j in range (len(move[i])):75 x = int(move[i][j]) - 176 basen += i * n**x77 return basen78 798081def createNewMove (oldmove, p1, p2):82 global n83 newmove = []84 for i in range (n):85 newmove.append(oldmove[i])86 87 newmove[p2] = newmove[p1][0:1] + newmove[p2]88 newmove[p1] = newmove[p1][1:]89 90 91 if p2 < p1 and newmove[p2][0:1] == str(n):92 return oldmove93 else:94 return newmove95 96def search(move):97 global n98 if done(move):99 return 0100 else:101 tree = []102 tree.append(Node(move,0)) 103 while len(tree) > 0: 104 x = tree.pop(0)105 for i in range(n):106 107 if i < n-1:108 if len(x.m[i+1]) == 0 or x.m[i][0:1] < x.m[i+1][0:1]:109 newmove = createNewMove(x.m, i, i+1)110 bn = movetoBaseN (newmove)111 if not visited[bn]:112 visited[bn] = True113 tree.append(Node(newmove,x.level + 1))114 if done(newmove):115 return x.level + 1116 117 if i > 0:118 if len(x.m[i-1]) == 0 or x.m[i][0:1] < x.m[i-1][0:1]:119 newmove = createNewMove(x.m, i, i-1)120 bn = movetoBaseN (newmove)121 if not visited[bn]:122 visited[bn] = True123 tree.append(Node(newmove,x.level + 1))124 if done(newmove):125 return x.level + 1126 127 return "IMPOSSIBLE" 128 129file = open("s4.5.in", 'r')130n = eval(file.readline().strip())131while n > 0:132 133 134 visited = []135 size = n**n136 for i in range(size + 1):137 visited.append(False)138 139 move = file.readline().strip().split()140 print search(move)141 n = eval(file.readline().strip())142