问:电梯停在哪一层楼,能够保证这次乘坐电梯的所有乘客爬楼梯的层数之和最少?
附上java的实现方式:
package test.alg;public class elevetor {//nPerson[i]表示在第i层下电梯的人数int[] nPerson = {0,2,5,7,8,9,6,6,1,4,4,8,5,2,4,5,8,6,3,3,5,9,9,6,6,9,8,8,5,5,9,6,6,3};int nMinFloor,nTargetFloor;//n2是在第i层下电梯的人数,n1是在第i层以下下电梯的人数,n3是在第i层以上 下电梯的人数int n1 = 0;int n2 = nPerson[1];int n3 = 0;int N = nPerson.length - 1;public void control(){for(int i = 2;i<=N;i++){n3 += nPerson[i];nMinFloor += nPerson[i] * (i-1);}for(int i = 2; i<=N;i++){if(n1 + n2 < n3){nTargetFloor = i;nMinFloor += n1+n2-n3;n1 += n2;n2 = nPerson[i];n3 -= nPerson[i];}else break;}System.out.println("把目标楼层定为:"+nTargetFloor);System.out.println("有最小值:"+nMinFloor);}public static void main(String[] args) {new elevetor().control();}}
待会在自己研究个其他的方法