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

标签 c# algorithm

我被问到一个问题,要求我编写一个最佳程序来确定一部电梯为 X 个人服务而停靠的总次数。问题描述如下。

在 M 层的建筑物中有一部电梯,该电梯一次最多可搭载 X 人或最大总重量 Y。假设一组人已经到达,并且他们的体重和他们需要到达的楼层考虑到电梯为所有人服务而停了多少站。按照先到先得的原则考虑电梯服务。

例如设数组 A 为要考虑的人的体重 A[] = {60, 80, 40 }

设数组B分别为需要下人的楼层 B[] = {2, 3, 5}

大楼总层数为 5,电梯一次最多允许 2 人,最大载重量为 200 对于此示例,电梯将总共停靠 5 个楼层 ground, 2, 3,ground, 5 , ground

对此的最佳代码是什么?

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

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;
    }
}

最佳答案

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

换句话说,这是一项非常重要的数学任务,在尝试编写一行代码之前,您应该真正专注于正确掌握数学知识。优化意味着获得最佳解决方案,而不仅仅是一些解决方案;)

关于c# - 确定电梯总停靠次数的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33885921/

相关文章:

c# - SQL 语句的某些部分嵌套太深。重写查询或将其分解为更小的查询

python - 递归困惑-砍杆算法

java - 当某些值必须晚于其他值出现时如何对列表进行排序,可能会忽略需要 'delaying' 的此类项目的排序顺序

c# - 将嵌套集合发布到 Web API

c# - 没有加载项 Express 的 outlook 2010 加载项构建自定义 WebViewPane

c# - 如何使用 HttpWebRequest 使 C# 应用程序表现得像 fiddler

用于测试扑克牌手牌的算法(4 到顺子)?

algorithm - 确定不可预测的非线性迭代算法的时间复杂度

Python - 如何找到两个向量之间的相关性?

c# - 如何从键盘移动 TableLayoutPanel 网格中的 PictureBox?