确定电梯总停靠次数的程序

本文关键字:程序 停靠 电梯 | 更新日期: 2023-09-27 18:23:59

有人问我一个问题,写一个最佳程序,确定电梯为X人服务的总停靠次数。问题描述如下。

在一栋M层的建筑里有一部电梯,这部电梯一次最多可以容纳X个人,或者最多可以容纳总重量Y。考虑到一组人已经到达,他们的重量和他们需要停的楼层,考虑到电梯为所有人服务需要停多少站。在先到先得的基础上考虑电梯发球。

例如,让数组A是要考虑的人的重量A[]={60,80,40}

设阵列B分别为需要落人的楼层B[]={2,3,5}

总建筑层数为5层,电梯一次最多允许2人,最大承重能力为200对于这个例子,电梯总共需要5个停靠楼层,地面,2,3,地面,5,地面

这方面的最佳代码是什么?

我的一个解决方案如下。还有其他更好的解决方案吗?

class Solution
{
    /// <summary>
    /// Return total stops used
    /// </summary>
    /// <param name="A">weight of people</param>
    /// <param name="B">floors they need to get down</param>
    /// <param name="M">total floors in the building</param>
    /// <param name="X">Max people to carry at a time</param>
    /// <param name="Y">max weight to carry at a time</param>
    /// <returns></returns>
    public int solution(int[] A, int[] B, int M, int X, int Y)
    {
        // write your code in C# 6.0 with .NET 4.5 (Mono)
        int totalStops = 0;
        long totalWeightPerRound = 0;
        int maxPersonsCount = 0;
        List<int> lstFloors = new List<int>();
        int currPerson = 0;
        bool startLift = false;
        while (currPerson < A.Length)
        {
            if ((totalWeightPerRound + A[currPerson]) <= Y && (maxPersonsCount+1) <= X)
            {
                totalWeightPerRound += A[currPerson];
                maxPersonsCount++;
                lstFloors.Add(B[currPerson]);
                if (currPerson == A.Length - 1)
                    startLift = true;
                currPerson++;
            }
            else
            {
                startLift = true;
            }
            if (startLift)
            {
                totalStops += lstFloors.Distinct().Count() + 1;
                lstFloors.Clear();
                maxPersonsCount = 0;
                totalWeightPerRound = 0;
                startLift = false;
            }
        }
        return totalStops;
    }
}

确定电梯总停靠次数的程序

也许有点偏离主题,但正如上面有人所说,这是一个数学问题,而不是编程问题。为了安全起见,你应该构造一个函数来描述你想要最小化的成本函数,添加约束以包括边界条件,最后计算变异以获得极值。

换句话说,这是一项不平凡的数学任务,在写一行代码之前,你应该真正专注于正确的数学运算。优化意味着得到最优解,而不仅仅是某个解;)