During peak hours, intern Xiaofei was often impatient to stop on every floor of the elevator, so he came up with a way: Because the floor is not high, so during busy hours, every time the elevator goes up from the first floor, we only allow the elevator to stop on one of them. All passengers are taken from the elevator upstairs. When they arrive at a certain floor, the elevator will hear that all passengers will climb the stairs from here to their target floor. On the first floor, each passenger chooses his or her target layer, and the elevator automatically calculates the floor to be stopped.
Q: Which floor does the elevator stop on? Can we ensure that the sum of the floors of all passengers who take the elevator to climb the stairs is the least?
# ! /Usr/bin/Python # Coding = UTF-8 Import Random, math From Itertools Import Groupbyfloor = 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, VIn 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 XIn 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> = N3And (Ntargetfloor = none Or Ntargetfloor = Floors ): Print " * " Return Floors Print Return Ntargetfloor If _ Name __ = ' _ Main __ ' : Main ()