在高峰时间,实习生小飞常常会被电梯每层楼都停弄得很不耐烦,于是他想出了这样一个办法:由于楼层并不高,那么在繁忙的时间,每次电梯从一层往上走时,我们只允许电梯停在其中的某一层。所有乘客都从一楼上电梯,到达某层楼后,电梯听下来,所有乘客再从这里爬楼梯到自己的目的层。在一楼时,每个乘客选择自己的目的层,电梯则自动计算出应停的楼层。
问:电梯停在哪一层楼,能够保证这次乘坐电梯的所有乘客爬楼梯的层数之和最少?
#! /usr/bin/python # coding=utf-8 import random,math from itertools import groupby floor = 5 def main(): arr = [random.randint(1,floor) for i in range(random.randint(3,5))] print arr do1(arr) do2(arr) def do1(arr): print "-" * 20 data = [(i,sum([abs(item - i) for item in arr])) for i in range(1,floor+1)] maxdata = min([item for index, item in data]) for index, item in data: print "%s,%s %s" % (index,item,"*" if item == maxdata else "") def do2(arr): print "-" * 20 arr = sorted(arr) nPerson = [0] * (floor + 1) for k,v in groupby(arr): nPerson[k] = len(list(v)) #print nPerson floors = sum([x - 1 for x in arr if x > 1]) n1,n2,n3 = 0, nPerson[1], sum(nPerson) - nPerson[1] nTargetFloor = format_print(1,n1,n2,n3,floors,None) for x in range(2,floor+1): floors += n1 + n2 - n3 n1 += n2 n2 = nPerson[x] n3 -= n2 nTargetFloor = format_print(x,n1,n2,n3,floors,nTargetFloor) def format_print(x,n1,n2,n3,floors, nTargetFloor): print x,n1,n2,n3,floors, if n1+n2 >= n3 and (nTargetFloor == None or nTargetFloor == floors): print "*" return floors print return nTargetFloor if __name__ == '__main__': main()