Title: "The Beauty of programming" P53
A number of passengers from an upstairs elevator, elevator, can only be docked in a certain level. Ask which floor the elevator is parked on, so that the total number of floors can be minimized for all passengers?
Analysis:
Elevators can be parked in the negative layer, but there is no 0 floor. So the program returns 0 o'clock, indicating an error. there is a trap here, because there is no 0 layer, so in the calculation, you should first put a negative number of floors plus 1. When the last calculated result is less than 0 o'clock, minus one, is the actual negative number of layers.
The elements of the array entered in the code represent the floors each passenger wants to go to. The best stopping floor must fall in the interval [Minfloor,maxfloor], where Minfloor represents the minimum value the passenger wants to go to the floor,maxfloor indicates the maximum value the passenger wants to go to the floor.
int Best_stop_floor (vector<int> N) {if (N.empty ()) return 0;//does not have a 0 layer, which indicates an error if (n.size () = = 1) return n[0];// Add 1for (auto& t:n) {if (T < 0) ++t for floors less than 1;} Sort (N.begin (), N.end ()), int minfloor = N.front (), Maxfloor = N.back (), int N1 = 0, N2 = 1,N3 = 0,index=1;//Determine if Minfloor is optimal solution int bestfloor = minfloor;while (Index < N.size () && n[index] = = N[0]) {++index;++n2;} N3 = N.size ()-n2;if (N1 + N2 < N3) ++bestfloor;for (int i=minfloor+1; i<=maxfloor; i++) {if (Index < n.size () &A mp;& i < N[index]) {N2 = 0; N1 = index; N3 = N.size ()-N1;} if (Index < n.size () && i = = N[index]) {N2 = 1; N1 = Index;int Prefloor = n[index];++index;while (Index < N.size () && n[index] = = Prefloor) {++index;++n2;} N3 = N.size ()-n1-n2;} if (N1 > N2 + N3) {if (Bestfloor >= i) Bestfloor = i-1;} else if (N1 + N2 < N3) {if (Bestfloor <= i) Bestfloor = i + 1;} Else{bestfloor = i;}} Note that this judgment condition if (bestfloor <= 0)--bestfloor;return Bestfloor;}
The elevator scheduling algorithm of "mathematics" small Flying