自动售货机出货系统
in Algorithm Pageviews
请设计一款自动售货机的出货管理系统,MachineSys(int trayNum, int trayCap) :设置该自动售货机上共有 trayNum 个商品轨道,每个商品轨道上最多可以放置 trayCap 个商品。
每个轨道上只能放置同一品牌的商品;同一品牌的商品只能放置在一个轨道上;
对于已经售空的轨道可以加入某一品牌的商品,即不一定是原品牌。
AddProduct(int brandId, vector<int> productIdList) :向系统中添加商品,品牌为 brandId,商品编号为 productIdList,从所在轨道的末端商品之后按数组 productIdList 下标升序依次放入。
售货机内已有该品牌的商品:若所在轨道剩余空间充足,则放入商品并返回 true;否则不做任何操作并返回 false;
售货机内没有该品牌商品:若售货机内有空轨道,且该轨道空间充足,则放入商品并返回 true;否则不做任何操作并返回 false;
BuyProduct(int brandId, int num):购买品牌为 brandId 的 num 个商品。
若有足够的商品,则取该轨道上前 num 个商品并返回其商品编号列表;
若没有该品牌的商品,或该商品数量不足 num 个,则不做任何操作,直接返回空数组
[]
QueryProduct():按照品牌编号升序返回每个品牌的首个商品编号(忽略空轨道);若售货机为空,则返回空数组
[]
示例1:
输入:[”MachineSystem“, “AddProduct”, “BuyProduct”, “QueryProduct”]
[[2, 5], [3, [3, 5, 4, 6, 2]], [3, 3], []]
输出:
[null, true, [3, 5, 4], [6]]
解释:
MachineSystem(2, 5); // 设置自动售货机共有 2 个轨道,每个轨道上只能放置 5 个商品。
obj.AddProduct(3, [3, 5, 4, 6, 2]); // 在售货机放置品牌编号为 3 的商品,按照下标升序依次放入,商品编号依次为 3、5、4、6、2,返回 true。
obj.BuyProduct(3, 3); // 购买3个品牌编号为 3 的商品,被购买的商品编号依次为3、5、4,返回所购商品编号列表 [3,5,4]
obj.QueryProduct(); // 当前只有 1 个品牌商品,其首个商品编号为 6,返回 [6]
注:输出中的 null 表示此对应函数无输出;
代码实现如下:
#include <bits/stdc++.h>
using namespace std;
class MachineSys {
public:
MachineSys(int trayNum, int trayCap)
: trayNum(trayNum), trayCap(trayCap), tray(map<int, vector<int>>())
{}
bool AddProduct(int brandId, const vector<int> &productIdList)
{
if ((tray.count(brandId) == 0) && (tray.size() < trayNum) && (productIdList.size() <= trayCap)) {
vector<int> pro(productIdList.begin(), productIdList.end());
tray[brandId] = pro;
return true;
}
if ((tray.count(brandId) != 0) && (tray[brandId].size() + productIdList.size() <= trayCap)) {
tray[brandId].insert(tray[brandId].end(), productIdList.begin(), productIdList.end());
return true;
}
return false;
}
vector<int> BuyProduct(int brandId, int num)
{
vector<int> res;
if ((tray.count(brandId) != 0) && (tray[brandId].size() >= num)) {
res.insert(res.end(), tray[brandId].begin(), tray[brandId].begin() + num);
tray[brandId].erase(tray[brandId].begin(), tray[brandId].begin() + num);
if (tray[brandId].empty()) {
tray.erase(brandId);
}
}
return res;
}
vector<int> QueryProduct()
{
vector<int> result;
for (auto it = tray.begin(); it != tray.end(); it++) {
result.push_back(it->second[0]);
}
return result;
}
private:
int trayNum;
int trayCap;
map<int, vector<int>> tray;
};