程式設計之美之一摞烙餅的問題
阿新 • • 發佈:2019-02-17
我對程式設計之美中一摞烙餅的問題中的演算法用Python實現了一遍,並且進行了優化,直接上程式碼吧:
#!/usr/bin/env python class PrefixSorting(object): def __init__(self, ): self._cakes = [] self._reverseCakes = [] self._maxSwap = 0 self._swaps = [] self._reverseSwap = [] self._search = 0 def run(self, cakes): self.init(cakes) self._search = 0; self.search(0) def outPut(self): print self._swaps print self._search print self._maxSwap def init(self, cakes): self._cakes = cakes[:] self._reverseCakes = cakes[:] self._maxSwap = self.upperBound(len(cakes)) self._swaps = [0]*self._maxSwap self._reverseSwap = [0]*self._maxSwap self._search = 0 def upperBound(self, cakeCount): return cakeCount*2 def lowerBound(self, cakes): result = 0 for i in range(len(cakes)-1): t = cakes[i+1] - cakes[i] if t > 1 or t < -1: result = result+1 return result def search(self, step): self._search = self._search + 1 estimate = self.lowerBound(self._reverseCakes) if step + estimate >= self._maxSwap: return reverseCakes = self._reverseCakes[:] reverseCakes.sort() if reverseCakes == self._reverseCakes: if step < self._maxSwap: self._cakes = self._reverseCakes[:] self._maxSwap = step self._swaps = self._reverseSwap[:self._maxSwap] self._swaps = self.normal(self._swaps[:]) self._maxSwap = len(self._swaps) return for i in range(len(self._cakes)-1): self.reverse(i+1) self._reverseSwap[step] = i+1 if step < len(self._reverseSwap) - 1: self._reverseSwap[step+1:] = [0]*(len(self._reverseSwap)-step-1) self.search(step+1) self.reverse(i+1) def reverse(self, i): if i < len(self._reverseCakes)-1: header = self._reverseCakes[0:i+1] header.reverse() self._reverseCakes = header+self._reverseCakes[i+1:] else: self._reverseCakes.reverse() def normal(self, swap): i = 0 while i < len(swap)-1: if swap[i] == swap[i+1]: swap[i:i+2]=[] i = i-1 if i > 0 else 0 else: i = i+1 return swap if __name__ == '__main__': pS = PrefixSorting() pS.run([3,2,1,6,5,4,9,8,7,0]) pS.outPut()
normal函式就是優化的地方。