今天遇到一个面试题, 金山的一个朋友问我的。 题目是这样的。
人们在酒店等电梯。酒店有0到M层楼。电梯有人数限制X, 载重限制为Y。 0层楼有N个人排队等到进入电梯。 每个人的体重存在数组A[K]中。他们各自的目标楼层是B[K]。 人们依次排队进入电梯,不能插队。电梯尽量一次载尽可能多的人上楼。在各个目标楼层放出乘客,之后返回0楼。 每次停靠在一个楼层,算一次停靠。返回0楼也算停靠一次。请设计一个计算电梯总共停靠次数的函数。
简单的写了个程序:
int solution(vector<int> &A, vector<int> &B, int M, int X, int Y)
{
// write your code in C++14 (g++ 6.2.0)
int count = A.size();
int ar_floor[100000] = { 0 }; // M
bool is_down = false;
int ret = 0;
if (count == 0)
return 0;
int total_weight = A[0];
ar_floor[B[0]] = 1;
++ret;
for (int i = 0; i < count -1; ++i)
{
int t = A[i + 1];
if (total_weight + A[i+1] > Y)
{
memset(ar_floor, 0, sizeof(ar_floor));
is_down = true;
++ret;
total_weight = A[i+1];
ar_floor[B[i + 1]] = 1;
++ret;
}
else
{
total_weight += A[i + 1];
if (ar_floor[B[i+1]] == 0)
{
ar_floor[B[i+1]] = 1;
++ret;
}
is_down = false;
}
}
if (is_down == false)
++ret;
return ret;
}