首页 > 试题广场 >

自动售货系统

[编程题]自动售货系统
  • 热度指数:31916 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
1 总体说明
考生需要模拟实现一个简单的自动售货系统,实现投币、购买商品、退币、查询库存商品及存钱盒信息的功能。
系统初始化时自动售货机中商品为6种商品,商品的单价参见1.1规格说明,存钱盒内放置1元、2元、5元、10元钱币,商品数量和钱币张数通过初始化命令设置,参见2.1 系统初始化。
1.1规格说明
1. 商品:每种商品包含商品名称、单价、数量三种属性,其中商品名不重复。考生不能修改商品名称和单价,初始化命令设置商品数量。这些信息在考试框架中进行定义,考生在实现功能代码时可直接使用。
商品 名称
单价
数量
A1 2 X
A2 3 X
A3 4 X
A4 5 X
A5 8 X
A6 6 X
2. 存钱盒信息:钱币面额、张数两种属性。初始化命令设置各种面额钱币张数。这些信息在考试框架中进行定义,考生在实现功能代码时可直接使用。
钱币面额
张数
10元
X
5元
X
2元 X
1元 X
3. 退币原则
1) 根据系统存钱盒内钱币的 信息 ,按钱币总张数最少的原则进行退币。
2) 如果因零钱不足导致不能退币,则尽最大可能退币,以减少用户损失。
例如:假设存钱盒内只有4张2元,无其它面额钱币。如果需要退币7元,系统因零钱不足无法退币,则继续尝试退币6元,最终系统成功退币3张2元,用户损失1元钱币。
4. 投币操作说明:每次投币成功,投入的钱币面额累加到投币余额;同时,本次投入的钱币放入存钱盒中,存钱盒相应面额钱币增加。
5. 投币余额:指当前自动售货机中用户剩余的可购买商品的钱币总额;例如:投入2元面额的钱币,投币余额增加2元;购买一件价格2元的商品,投币余额减少2元;
6. 退币操作说明:退币操作需要遵守 退币原则 ;退币成功后,投币余额清零,同时扣除存钱盒相应的金额。
7. 购买商品操作说明:一次仅允许购买一件商品;购买商品成功后,自动售货机中对应商品数量减1,投币余额扣除本次购买商品的价格。
2 操作说明
命令字与第一个参数间使用一个空格分隔,多条命令采用分号隔开。考试系统会对输入命令格式进行处理,考生不需要关注输入命令格式的合法性,只需要实现命令处理函数。
2.1 系统初始化
命令格式
r A1 数量 -A2 数量 -A3 数量 -A4 数量 -A5 数量 -A6 数量 1 元张数 -2 元张数 -5 元张数 -10 元张数
参数名称
参数说明
类型
取值范围
A1数量
商品A1数量
整数
[0,30]
A2数量
商品A2数量
整数
[0,30]
A3数量
商品A3数量
整数
[0,30]
A4数量
商品A4数量
整数
[0,30]
A5数量
商品A5数量
整数
[0,30]
A6数量
商品A6数量
整数
[0,30]
1元张数
面额1元钱币张数
整数
[0,30]
2元张数
面额2元钱币张数
整数
[0,30]
5元张数
面额5元钱币张数
整数
[0,30]
10元张数
面额10元钱币张数
整数
[0,30]
商品和各种面额钱币取值范围只是作为初始化命令的限制,其它场景下不限制取值范围;考试框架已经实现取值范围的检查,考生不需要关注。
功能说明:设置自动售货机中商品数量和存钱盒各种面额的钱币张数;
约束说明:系统在任意阶段均可执行r初始化系统;考生不需要关注参数的合法性,不需要关注增加或缺少参数的场景;
输出说明:输出操作成功提示(执行完r命令后系统会自动输出操作结果,考生不需要再次调用输出函数),例:
命令 输出 含义
r 6-5-4-3-2-1 4-3-2-1; S001:Initialization is successful 初始化成功
2.2 投币
命令格式p 钱币面额
功能说明
(1) 如果投入非1元、2元、5元、10元的钱币面额(钱币面额不考虑负数、字符等非正整数的情况),输出“E002:Denomination error”;
(2) 如果存钱盒中1元和2元面额钱币总额小于本次投入的钱币面额,输出“E003:Change is not enough, pay fail”,但投入1元和2元面额钱币不受此限制。
(3) 如果自动售货机中商品全部销售完毕,投币失败。输出“E005:All the goods sold out”;
(4) 如果投币成功,输出“S002:Pay success,balance=X”;
约束说明
(1) 系统在任意阶段都可以投币;
(2) 一次投币只能投一张钱币;
(3) 同等条件下,错误码的优先级:E002 > E003 > E005;
输出说明:如果投币成功,输出“S002:Pay success,balance=X”。
例:
命令
输出
p 10;
S002:Pay success,balance=10
2.3 购买商品
命令格式b 商品名称
功能说明
(1) 如果购买的商品不在商品列表中,输出“E006:Goods does not exist”;
(2) 如果所购买的商品的数量为0,输出“E007:The goods sold out”;
(3) 如果投币余额小于待购买商品价格,输出“E008:Lack of balance”;
(4) 如果购买成功,输出“S003:Buy success,balance=X”;
约束说明
(1) 一次购买操作仅能购买一件商品,可以多次购买;
(2) 同等条件下,错误码的优先级:E006 > E007 > E008;
输出说明:
如果购买成功,输出“S003:Buy success,balance=X”。
例:
命令
输出
b A1;
S003:Buy success,balance=8
2.4 退币
命令格式c
功能说明
(1) 如果投币余额等于0的情况下,输出“E009:Work failure”;
(2) 如果投币余额大于0的情况下,按照 退币原则 进行“找零”,输出退币信息;
约束说明
(1) 系统在任意阶段都可以退币;
(2) 退币方式必须按照 退币原则 进行退币;
输出说明:如果退币成功,按照 退币原则 输出退币信息。
例,退5元钱币:
命令
输出
c;
1 yuan coin number=0
2 yuan coin number=0
5 yuan coin number=1
10 yuan coin number=0
2.5 查询
命令格式q 查询类别
功能说明
(1) 查询自动售货机中商品信息,包含商品名称、单价、数量。 根据商品数量从大到小进行排序;商品数量相同时,按照商品名称的先后顺序进行排序
例如:A1的商品名称先于A2的商品名称,A2的商品名称先于A3的商品名称。
(2) 查询存钱盒信息,包含各种面额钱币的张数;
(3) 查询类别如下表所示:
查询类别
查询内容
0
查询商品信息
1 查询存钱盒信息
如果“查询类别”参数错误,输出“E010:Parameter error”。“查询类别”参数错误时,不进行下面的处理;
输出说明
“查询类别”为0时,输出自动售货机中所有商品信息(商品名称单价数量)例:
命令
输出
q 0;
A1 2 6
A2 3 5
A3 4 4
A4 5 3
A5 8 2
A6 6 0
“查询类别”为1时,输出存钱盒信息(各种面额钱币的张数),格式固定。例:
命令
输出
q 1;
1 yuan coin number=4
2 yuan coin number=3
5 yuan coin number=2
10 yuan coin number=1


输入描述:

依照说明中的命令码格式输入命令。



输出描述:

输出执行结果

示例1

输入

r 22-18-21-21-7-20 3-23-10-6;c;q0;p 1;b A6;c;b A5;b A1;c;q1;p 5;

输出

S001:Initialization is successful
E009:Work failure
E010:Parameter error
S002:Pay success,balance=1
E008:Lack of balance
1 yuan coin number=1
2 yuan coin number=0
5 yuan coin number=0
10 yuan coin number=0
E008:Lack of balance
E008:Lack of balance
E009:Work failure
E010:Parameter error
S002:Pay success,balance=5

题目描述

总体说明
考生需要模拟实现一个简单的自动售货系统,实现投币、购买商品、退币、查询库存商品及存钱盒信息的功能。
系统初始化时自动售货机中商品为6种商品,商品的单价参见1.1规格说明,存钱盒内放置1元、2元、5元、10元钱币,商品数量和钱币张数通过初始化命令设置,参见2.1 系统初始化。
1.1 规格说明
1.        商品:每种商品包含商品名称、单价、数量三种属性,其中商品名不重复。考生不能修改商品名称和单价,初始化命令设置商品数量。这些信息在考试框架中进行定义,考生在实现功能代码时可直接使用。
 

输入描述:
		

依照说明中的命令码格式输入命令。



输出描述:
		

输出执行结果


输入例子:
r 1-1-1-1-1-1 10-5-2-1;p 1;q 1;

输出例子:
S001:Initialization is successful
S002:Pay success,balance=1
1 yuan coin number=11
2 yuan coin number=5
5 yuan coin number=2
10 yuan coin number=1
说明中哪里介绍命令码格式了?根据输入用例也看不出来格式的含义啊,
希望管理员把华为这个系列好好修复,错误太多了。
发表于 2016-04-16 21:40:25 回复(0)
草,init的时候没有清零投币余额卡了我半天
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
string daigoumai;
int A[6] = {0,0,0,0,0,0};
const int A_price[6] = {2,3,4,5,8,6};
int ZS[5] = {0,0,0,0,0};
bool q_right;
int toubiyue;
char chaxunleixing;
void init(vector<int> vec){
    toubiyue = 0;
    A[0] = vec[0];A[1] = vec[1];A[2] = vec[2];
    A[3] = vec[3];A[4] = vec[4];A[5] = vec[5];
    ZS[0] = vec[6];ZS[1] = vec[7];
    ZS[2] = vec[8];ZS[3] = vec[9];
    cout<<"S001:Initialization is successful"<<endl;
    return;
}
void chaxun(){
    if(!q_right){
        cout<<"E010:Parameter error"<<endl;
    }
    else{
        if(chaxunleixing = '0'){
            cout<<"A1 "<<A_price[0]<<' '<<A[0]<<endl;
            cout<<"A2 "<<A_price[1]<<' '<<A[1]<<endl;
            cout<<"A3 "<<A_price[2]<<' '<<A[2]<<endl;
            cout<<"A4 "<<A_price[3]<<' '<<A[3]<<endl;
            cout<<"A5 "<<A_price[4]<<' '<<A[4]<<endl;
            cout<<"A6 "<<A_price[5]<<' '<<A[5]<<endl;
        }
        else{
            cout<<"1 yuan coin number="<<ZS[0]<<endl;
            cout<<"2 yuan coin number="<<ZS[1]<<endl;
            cout<<"5 yuan coin number="<<ZS[2]<<endl;
            cout<<"10 yuan coin number="<<ZS[3]<<endl;
        }
    }
    return;
}
void tuibi(){
    if(toubiyue==0){
        cout<<"E009:Work failure"<<endl;
    }
    else{
        int shenyulinq;
        shenyulinq = ZS[0] + 2*ZS[1] + 5*ZS[2] + 10*ZS[3];
        if(shenyulinq<=toubiyue){
            cout<<"1 yuan coin number="<<ZS[0]<<endl;
            cout<<"2 yuan coin number="<<ZS[1]<<endl;
            cout<<"5 yuan coin number="<<ZS[2]<<endl;
            cout<<"10 yuan coin number="<<ZS[3]<<endl;
            
        }
        else{
            int tb_1 = 0,tb_2 = 0,tb_5 = 0,tb_10 = 0;
            while(toubiyue>=0){
                if(ZS[3]&&toubiyue-10>=0){//先退10元
                    ZS[3]--;
                    toubiyue-=10;
                    tb_10++;
                }
                else if(ZS[2]&&toubiyue-5>=0){
                    ZS[2]--;
                    toubiyue-=5;
                    tb_5++;
                }
                else if(ZS[1]&&toubiyue-2>=0){
                    ZS[1]--;
                    toubiyue-=2;
                    tb_2++;
                }
                else if(ZS[0]&&toubiyue-1>=0){
                    ZS[0]--;
                    toubiyue-=1;
                    tb_1++;
                }
                if(toubiyue==0) break;
            }
            cout<<"1 yuan coin number="<<tb_1<<endl;
            cout<<"2 yuan coin number="<<tb_2<<endl;
            cout<<"5 yuan coin number="<<tb_5<<endl;
            cout<<"10 yuan coin number="<<tb_10<<endl;
        }
        toubiyue = 0;
    }
    return;
}
void goumai(){
    if(daigoumai!="A1"&&daigoumai!="A2"&&daigoumai!="A3"&&
      daigoumai!="A4"&&daigoumai!="A5"&&daigoumai!="A6"){
        cout<<"E006:Goods does not exist"<<endl;
    }
    else if(A[daigoumai[1]-'0'-1]==0){
        cout<<"E007:The goods sold out"<<endl;
    }
    else if(toubiyue<A_price[daigoumai[1]-'0'-1]){
        cout<<"E008:Lack of balance"<<endl;
    }
    else{
        toubiyue-=A_price[daigoumai[1]-'0'-1];
        A[daigoumai[1]-'0'-1]--;
        cout<<"S003:Buy success,balance="<<toubiyue<<endl;
    }
    return;
}
void tb(vector<int> vec){
    if(vec[0]!=1&&vec[0]!=2&&vec[0]!=5&&vec[0]!=10){
        cout<<"E002:Denomination error"<<endl;
    }
    else if((vec[0]==5||vec[0]==10)&&(ZS[0]+ZS[1]*2<vec[0])){
        cout<<"E003:Change is not enough, pay fail"<<endl;
    }
    else if(A[0]==0&&A[1]==0&&A[2]==0&&A[3]==0&&A[4]==0&&A[5]==0){
        cout<<"E005:All the goods sold out"<<endl;
    }
    else{
        toubiyue+=vec[0];
        switch(vec[0]){
            case 1:{
                ZS[0]++;
                break;
            }
            case 2:{
                ZS[1]++;
                break;
            }
            case 5:{
                ZS[2]++;
                break;
            }
            case 10:{
                ZS[3]++;
                break;
            }
            default:{
                break;
            }
        }
        cout<<"S002:Pay success,balance="<<toubiyue<<endl;
    }
    return;
}
int judge_command(string str,vector<int> &a){
    a.clear();
    int len = str.length();
    if(len<=0) return -1;
    else if(len==1&&str[0]=='c') return 4;
    else switch(str[0]){
        case 'r':{
            int sum = 0;
            for(int i = 1;i< len;i++){
                if(str[i]!=' '||str[i]!='-'){
                    if(isdigit(str[i])){
                        sum=sum*10+str[i]-'0';
                        i++;
                        while(i<len&&isdigit(str[i])){
                            sum=sum*10+str[i]-'0';
                            i++;
                        }
                        a.push_back(sum);
                        sum = 0;
                    }
                }
            }
            return 1;
            break;
        }
        case 'p':{
            bool flag = false;
            int miane = 0;
            if(str[1]!=' ') return -1;
            for(int i = 1;i < len;i++){
                if(isdigit(str[i])){
                    if(flag) return -1;
                    miane = miane*10+str[i]-'0';
                    i++;
                    while(i<len&&isdigit(str[i])){
                       miane=miane*10+str[i]-'0';
                        i++;
                    }
                    a.push_back(miane);
                    flag = true;
                }
            }
            return 2;
            break;
        }
        case 'b':{
            if(str[1]!=' ') return -1;
            string tmp_b;
            int st_pos,ed_pos;
            for(int i = 1;i< len;i++){
                if(str[i]!=' '){
                    st_pos = i;
                    while(i<len&&str[i]!=' '){
                        i++;
                    }//存疑
                    
                    i--;
                    ed_pos = i;
                    daigoumai = str.substr(st_pos,ed_pos-st_pos+1);
                }
            }
            return 3;
            break;
        }
        case 'q':{
            q_right = true;
            if(len!=3) q_right = false;
            else if(str[1]!=' ') q_right = false;
            else if(str[2]!='0'&&str[2]!='1') q_right = false;
            else{
                chaxunleixing = str[2];
            }
            return 5;
            break;
        }
    }
    return -1;
}
int main(){
    string str1,tmp;
    vector<int> tmp_cans;
    toubiyue = 0;
    while(getline(cin, str1)){
        vector<string> vec;//存放命令
        stringstream ss;
        ss<<str1;
        while(getline(ss, tmp,';')){
            vec.push_back(tmp);
        }
        for(int i = 0;i < vec.size();){//处理第i条命令vec[i]
            switch(judge_command((vec[i]),tmp_cans)){
                case 1://初始化
                    init(tmp_cans);
                    break;
                case 2://投币
                    tb(tmp_cans);
                    break;
                case 3://购买商品
                    goumai();
                    break;
                case 4://退币
                    tuibi();
                    break;
                case 5://查询
                    chaxun();
                    break;
                default:
                    break;
            }
            vec.erase(vec.begin());
        }
    }
    return 0;
}


发表于 2022-02-19 17:57:42 回复(0)
苦肝一下午终于做出来了,只用的菜鸡解法,全局变量记得要每次init;
// 存钱盒  投币余额 各种面额钱币张数 
#include<cstring>
#include<bits/stdc++.h>
using namespace std;

typedef struct {
    int hao;   // 只存序号
    int price;
    int num;    
}Prod;
typedef struct {
    int hao;
    int num;
}Face;

vector<Prod> prod(6);
vector<Face> face(4);
int spare = 0;  // 唯一一个单独的全局变量:‘投币余额’
void init(string s);
void back(string s);
void query(string s);
void in(string s);
void buy(string s);
int main() {
    string line;
    while (getline(cin, line)) {
        stringstream ss(line);
        string s;
        while (getline(ss, s, ';')) {
            if (s[0] == 'r') init(s);
            if (s[0] == 'c') back(s);
            if (s[0] == 'q') query(s);
            if (s[0] == 'p') in(s);
            if (s[0] == 'b') buy(s);
        }
    }
}

void init(string s) {
    spare=0;
    s = s.substr(2);
    int pos = s.find(' ');
    string str1 = s.substr(0, pos), str2 = s.substr(pos + 1);
    stringstream ss1(str1), ss2(str2);
    char punc = '-';       // 这里有个疑问是,ss1中类型并非int、是如何传输成功的?// 但是VS里面传输失败,只有在牛客能成功
    ss1 >> prod[0].num >> punc >> prod[1].num >> punc >> prod[2].num >> punc >> prod[3].num >> punc >> prod[4].num >> punc >> prod[5].num;
    ss2 >> face[0].num >> punc >> face[1].num >> punc >> face[2].num >> punc >> face[3].num;
    for (int i = 0; i < 6; i++) prod[i].hao = i;
    prod[0].price = 2; prod[1].price =3; prod[2].price = 4; prod[3].price = 5; prod[4].price = 8; prod[5].price = 6;
    face[0].hao = 1; face[1].hao = 2; face[2].hao = 5; face[3].hao = 10;
    cout << "S001:Initialization is successful" << endl;
}

void back(string s) {
    int sum=0;
    int backCot[4] = {0};
    if (spare == 0) cout << "E009:Work failure" << endl;
    else if(spare>0){
        for(int i=3;i>=0;i--){
            int face_num = face[i].num;
            for(int j=0;j<face_num;j++){
                if(face[i].hao>spare) break;
                if(sum+face[i].hao<=spare){
                    sum += face[i].hao;
                    face[i].num--;
                    backCot[i]++;
                }
            }
        }
        spare -= sum;
        for(int i=0;i<4;i++){
            cout<<face[i].hao<<" yuan coin number="<<backCot[i]<<endl;
        }
    }
    
}
bool cmp(Prod a, Prod b) {
    if (a.num != b.num) return a.num > b.num;
    return a.hao < b.hao;
}

void query(string s) {
    if (s.size() <= 2) {
        cout << "E010:Parameter error"<<endl;
        return;
    }
    else if (s[2] == '0') {
        sort(prod.begin(), prod.end(), cmp);
        for (int i = 0; i < 6; i++) cout << 'A' << prod[i].hao + 1 <<' '<< prod[i].price << ' ' << prod[i].num<<endl;
    }
    else if (s[2] == '1') {
        for (int i = 0; i < 4; i++)
            cout << face[i].hao << " yuan coin number=" << face[i].num << endl;
    }
    else 
        cout << "E010:Parameter error" << endl;
}
void in(string s){
    int sN = stoi(s.substr(2));
    bool limit = true,exist=false;
    if(sN == 1 || sN == 2) limit = false;
    for(int i=0;i<6;i++){
        if(prod[i].num >0) exist=true;
    }
    if((sN>2 && sN<5)||(sN>5 &&sN<10)|| (sN>10)) cout<<"E002:Denomination error"<<endl;
    else if((face[0].num + face[1].num*2 < sN) && limit) cout<<"E003:Change is not enough, pay fail"<<endl;
    else if(!exist) cout<<"E005:All the goods sold out"<<endl;
    else{  // 投币成功!
        for(int i=0;i<4;i++){
            if(face[i].hao == sN) face[i].num++;
        }
        spare += sN;  // 投币余额
        cout<<"S002:Pay success,balance="<<spare<<endl;
    }
}
void buy(string s){
    int hao = stoi(s.substr(3));   // 先只提取hao,不包括‘A’
    bool exist=false,nums=false;
    for(int i=0;i<6;i++){
        if(i+1 == hao) exist=true;
    }
    if(!exist) cout<<"E006:Goods does not exist"<<endl;
    else if(prod[hao-1].num==0) cout<<"E007:The goods sold out"<<endl;
    else if(spare < prod[hao-1].price) cout<<"E008:Lack of balance"<<endl;
    else{
        spare -= prod[hao-1].price;  // 投币余额得减掉了
        cout<<"S003:Buy success,balance="<<spare<<endl;
    }
}

发表于 2022-01-10 18:32:04 回复(0)
goods = {
    'A1': {'name':'A1', 'price':2, 'count':0},
    'A2': {'name':'A2', 'price':3, 'count':0},
    'A3': {'name':'A3', 'price':4, 'count':0},
    'A4': {'name':'A4', 'price':5, 'count':0},
    'A5': {'name':'A5', 'price':8, 'count':0},
    'A6': {'name':'A6', 'price':6, 'count':0},
}

moneys ={
    0: {'name':1, 'count':0},
    1: {'name':2, 'count':0},
    2: {'name':5, 'count':0},
    3: {'name':10, 'count':0},
}
surplus = 0

def initial(info):
    """
        根据用户输入的命令初始化商品和面额钱币的数量
    """
    data = []
    li0 = info[0].split('-')
    li1 = info[1].split('-')
    for i in li0:
        data.append(int(i))
    for j,v in zip(data,goods):
        goods[v]['count'] = j
    data = []
    for k in li1:
        data.append(int(k))
    for m,n in zip(data,moneys):
        moneys[n]['count'] = m 
    print('S001:Initialization is successful')


def buyGoods(arges):   # arges商品名称
    """
        购买商品:
            1.商品在商品列表/商品不在商品列表(字典)
            2.商品数量为0/商品数量不为0
            3.投币余额<购买的商品/投币余额>购买的商品
    """
    global surplus     # surplus 投币余额
    ingoods = arges[0]
    if ingoods in goods.keys():
        if goods[ingoods]['count'] != 0:
            if surplus >= goods[ingoods]['price']:
                surplus = surplus - goods[ingoods]['price']
                goods[ingoods]['count'] = goods[ingoods]['count']-1
                print('S003:Buy success,balance=%s' % surplus)
            else:
                print('E008:Lack of balance')
        else:
            print('E007,The goods sold out')
    else:
        print('E006,Goods does not exsit')
        
        
def payCoin(info):
    """
        投币:
            1.投币面额值是否准确
            2.商品数量是否为0
    """
    global surplus
    inmoneys = int(info[0])
    surplus = inmoneys + int(surplus)
    if inmoneys in [1,2,5,10]:
        if inmoneys < (moneys[0]['count'] + moneys[1]['count']*2):
            # if surplus <= 10:
            for i in goods.values():
                if i['count'] != 0:
                    break
            else:
                print('E005:All the goods sold out')
            for i in moneys.values():
                if inmoneys == i['name']:
                    i['count'] += 1
            print('S002:Pay success,balance=%d' % surplus)
        else:
            print('E003:Change is not enough,pay fail')
    else:
        print('E002:Denomination error')
    
    
def returnCoin():
    """
        退币:
            1.退币原则
                1) 根据系统存钱盒内钱币的信息,按钱币总张数最少的原则进行退币。
                2) 如果因零钱不足导致不能退币,则尽最大可能退币,以减少用户损失。
            2.投币余额等于0/投币余额>0
    """
    global surplus
    # print(surplus)
    li = [3,2,1,0]
    num = []
    if surplus != 0:
        if surplus > 0:
            for i in li:
                if surplus >= moneys[i]['name']:
                    if int(surplus/moneys[i]['name'])<=moneys[i]['count']:
                        num.append(int(surplus/moneys[i]['name']))
                        # print('%d yuan coin number=%d' % (moneys[i]['name'], int(surplus/moneys[i]['name'])))
                        surplus = surplus - (int(surplus/moneys[i]['name'])*moneys[i]['name'])
                    else:
                        num.append(int(moneys[i]['count']))
                        # print('%d yuan coin number=%d' % (moneys[i]['name'],moneys[i]['count']))
                        surplus = surplus - (moneys[i]['name'] * moneys[i]['count'])
                        
                else:
                    num.append(0)
                    # print('%d yuan coin number=0' % (moneys[i]['name']))
            result = zip(reversed(li),reversed(num))
            for (a,b) in result:
                print('%d yuan coin number=%d' % (moneys[a]['name'], b))
    else:
        print('E009:Work failure')
    
    
def queryGoods(info):
    """
        查询:0:商品信息
            1:存钱盒信息
    """
    if info[0] == '0':
        li = sorted(goods.values(), key=lambda v: (v['count'], v['price']), reverse=True)
        for i in li:
            print(list(i.values()))
    elif info[0] == '1':
        for coin in moneys.values():
            print('%d yuan coin number = %d' % (coin['name'], coin['count']))
    else:
        print('E010:Parameter error')


while True:
    try:
        surplus = 0
        comList = input().split(';')
        # comList = command.split(';')
        comAlpha = ['r', 'b', 'p', 'c', 'q']
        for com in comList:
            com2 = com.split(' ')
            if com2[0] == 'r':
                initial(com2[1:])
            elif com2[0] == 'b':
                buyGoods(com2[1:])
            elif com2[0] == 'p':
                payCoin(com2[1:])
            elif com2[0] == 'c':
                returnCoin()
            elif com2[0] == 'q':
                queryGoods(com2[1:])
            elif com2[0]=='q0'&nbs***bsp;com2[0]=='q1':
                print('E010:Parameter error')
            else:
                break
        
    except:
        break
这是我的代码,有两条用例没通过,不知道是代码的问题,还是用例的问题,代码确实稍微有点缺陷(输入命令C后,没有更新moneys字典中的钱币数量,但是好像对输出结果没啥影响),有问题的用例如下:
用例:
r 6-2-28-19-15-10 7-26-24-7;q0;b A2;c;q0;b A4;q1;b A5;q0;b A2;b A6;c;b A5;q1;q0;p 5;p 10;p 2;c;q0;p 2;p 5;q1;q1;p 5;p 5;c;p 5;p 1;b A3;p 5;c;b A3;p 5;
(这条我实在找不出哪里的问题了)
预期输出:
S001:Initialization is successful
E010:Parameter error
E008:Lack of balance
E009:Work failure
E010:Parameter error
E008:Lack of balance
E010:Parameter error
E008:Lack of balance
E010:Parameter error
E008:Lack of balance
E008:Lack of balance
E009:Work failure
E008:Lack of balance
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=5
S002:Pay success,balance=15
S002:Pay success,balance=17
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=1
E010:Parameter error
S002:Pay success,balance=2
S002:Pay success,balance=7
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=12
S002:Pay success,balance=17
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=1
S002:Pay success,balance=5
S002:Pay success,balance=6
S003:Buy success,balance=2
S002:Pay success,balance=7
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=0
E008:Lack of balance
S002:Pay success,balance=5
实际输出:
S001:Initialization is successful
E010:Parameter error
E008:Lack of balance
E009:Work failure
E010:Parameter error
E008:Lack of balance
E010:Parameter error
E008:Lack of balance
E010:Parameter error
E008:Lack of balance
E008:Lack of balance
E009:Work failure
E008:Lack of balance
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=5
S002:Pay success,balance=15
S002:Pay success,balance=17
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=1
E010:Parameter error
S002:Pay success,balance=2
S002:Pay success,balance=7
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=12
S002:Pay success,balance=17
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=1
S002:Pay success,balance=5
S002:Pay success,balance=6
S003:Buy success,balance=2
S002:Pay success,balance=7
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=0
E008:Lack of balance
S002:Pay success,balance=5

用例:
r 26-3-26-2-14-10 2-1-15-18;p 5;c;c;p 2;c;b A4;c;q1;q0;p 2;b A4;p 5;q0;c;q0;q1;q0;c;c;p 10;p 1;q0;
(感觉这条用例的预期结果这里少了一个1,实际输出应该是S002:Pay success,balance=11
预期输出:
S001:Initialization is successful
E003:Change is not enough, pay fail
E009:Work failure
E009:Work failure
S002:Pay success,balance=2
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=0
10 yuan coin number=0
E008:Lack of balance
E009:Work failure
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=2
E008:Lack of balance
S002:Pay success,balance=7
E010:Parameter error
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=0
E010:Parameter error
E010:Parameter error
E010:Parameter error
E009:Work failure
E009:Work failure
E003:Change is not enough, pay fail
S002:Pay success,balance=1
E010:Parameter error
实际输出:
S001:Initialization is successful
E003:Change is not enough,pay fail
1 yuan coin number=0
2 yuan coin number=0
5 yuan coin number=1
10 yuan coin number=0
E009:Work failure
S002:Pay success,balance=2
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=0
10 yuan coin number=0
E008:Lack of balance
E009:Work failure
E010:Parameter error
E010:Parameter error
S002:Pay success,balance=2
E008:Lack of balance
S002:Pay success,balance=7
E010:Parameter error
1 yuan coin number=0
2 yuan coin number=1
5 yuan coin number=1
10 yuan coin number=0
E010:Parameter error
E010:Parameter error
E010:Parameter error
E009:Work failure
E009:Work failure
E003:Change is not enough,pay fail
S002:Pay success,balance=11
E010:Parameter error

发表于 2021-09-11 18:03:22 回复(1)
有没有大佬会用matlab写这个啊?QAQ 这难度仿佛我的大作业。。。
这题和购物车都没有matlab大佬的代码,是matlab会超时吗?QAQ

发表于 2021-02-25 11:48:03 回复(1)
测试用例
r 1-1-10-16-11-12 2-15-26-9;p 5;q1;c;b A1;p 10;p 10;c;c;c;p 10;q1;p 1;c;b A3;q1;c;p 5;c;b A1;p 5;c;p 5;q0;c;p 10;q0;p 2;b A5;q1;b A5;b A6;p 10;c;p 2;c;q1;b A2;q0;
r 8-19-29-18-25-20 30-23-1-6;c;p 5;c;b A1;b A6;c;b A5;b A2;q0;b A5;q0;p 10;q0;p 2;b A1;q1;p 1;c;q0;q1;c;p 10;b A1;b A3;b A5;p 10;q1;q1;c;q1;q0;p 1;p 2;q0;

其中第76行输出是“E010:Parameter erro”, 少了个’r‘,这是怎么来的🤣


编辑于 2021-02-08 20:44:44 回复(0)
这个test case 有毒。。。
最后一个test case 的 结果的第24行估计是设置这个时候提前按了一个回车。。。
具体请看输出结果对比图。。。




!!!! nmd  最后那个 “r” 怎么去下一行了。。。。
只能等着他们把这个bug修好了再跑吧。。。

同时我也试了其他人给的答案,都没跑通,估计是他偷偷摸摸有把test case改了。。。

附赠一份我写的code
一个 class 直接建立一个对象
退钱的方程用了DP,实际上可以用贪心,不过差距不大啦

"""
Created on Tue Dec 22 07:53:19 2020

@author: legen
"""

class Machine(object):
    def __init__(self, arr):
        self.products = arr[0]
        self.changes = arr[1]
        self.price = [2,3,4,5,8,6]
        self.balance = 0
        print("S001:Initialization is successful")
    
    def insertMoney(self, coin):
        if coin not in [1,2,5,10]:
            print("E002:Denomination error")
            return
        if coin in [5, 10]:
            if self.changes[0] + self.changes[1]*2 < coin:
                print("E003:Change is not enough, pay fail")
                return
        if sum(self.products) == 0:
            print("E005:All the goods sold out")
            return
        h = {1:0, 2:1, 5:2, 10:3}
        self.changes[h[coin]] += 1
        self.balance += coin
        print("S002:Pay success,balance={}".format(self.balance))
        return
    
    def buy(self, item):
        h = {'A1':0, 'A2':1, 'A3':2, 'A4':3, 'A5':4, 'A6':5}
        if item not in h:
            print("E006:Goods does not exist")
            return
        if self.products[h[item]] == 0:
            print("E007:The goods sold out")
            return
        if self.price[h[item]] > self.balance:
            print("E008:Lack of balance")
            return
        self.products[h[item]] -= 1
        self.balance -= self.price[h[item]]
        print("S003:Buy success,balance={}".format(self.balance))
        return
    
    def popChange(self):
        if self.balance == 0:
            print("E009:Work failure")
            return
        self._combination()
        return
    
    def _combination(self):
        val = [1,2,5,10]
        f = [[None] * 4 for y in range(self.balance+1)]
        for i in range(self.balance+1):
            if i == 0:
                for j in range(4):
                    f[i][j] = 0
                continue
            for j in range(len(val)):
                if i >= val[j]:
                    if f[i-val[j]][j] + 1 <= self.changes[j]:
                        if f[i-val[j]][0] is not None:
                            prev = sum(f[i-val[j]])
                        else:
                            continue
                        if f[i][0] is None:
                            for k in range(4):
                                f[i][k] = f[i-val[j]][k]
                            f[i][j] += 1
                        else:
                            if sum(f[i]) > prev+1:
                                for k in range(4):
                                    f[i][k] = f[i-val[j]][k]
                                f[i][j] += 1
        for i in range(len(f)-1, -1, -1):
            if f[i][0] is not None:
                for j in range(4):
                    print("{} yuan coin number={}".format(val[j], f[i][j]))
                    self.changes[j] -= f[i][j]
                break
        self.balance = 0
        return
    
    def queryItem(self):
        name = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6']
        arr = [list(x) for x in zip(name, self.price, self.products)]
        arr.sort(key=lambda x: -x[2])
        for ele in arr:
            print(" ".join([str(x) for x in ele]))
        return
    
    def queryChange(self):
        val = [1,2,5,10]
        for i in range(len(self.changes)):
            print("{} yuan coin number={}".format(val[i], self.changes[i]))
        return

def vendingMachineOperation(jobs):
    for job in jobs:
        if job[0] == 'r':
            M = Machine([list(map(int, ele.split('-'))) for ele in job[1:]])
        elif job[0] == 'p':
            M.insertMoney(int(job[-1]))
        elif job[0] == 'b':
            M.buy(job[-1])
        elif job[0] == 'c':
            M.popChange()
        elif job[0] == 'q':
            if job[1] == 0:
                M.queryItem()
            elif job[1] == 1:
                M.queryChange()
            else:
                print("E010:Parameter error")
        else:
            print("E010:Parameter error")
    return


while True:
    try:
        jobs = list(input().split(';'))[:-1]
        jobs = [list(x.split()) for x in jobs]
        vendingMachineOperation(jobs)
    except:
        break


编辑于 2020-12-22 22:23:09 回复(1)

我有点怀疑在线测试的正确性
自己在本地测试,用的用例和在线测试一样,没有错误。只是少了末尾那个莫名其妙的初始化。
下面是我的代码(python 3):

class Goods(object):
    """Goods Class"""
    def __init__(self, name = 'g', price = 0, count = 0):
        self.name = name
        self.price = price
        self.count = count
    def set_count(self, c):
        self.count = c
class Cash(object):
    """Cash Class"""
    def __init__(self, name = 'yuan', denomination = 0, count = 0):
        self.name = name
        self.denomination = denomination
        self.count = count
    def set_count(self, c):
        self.count = c
shelf = {'A1':2, 'A2':3, 'A3':4, 'A4':5, 'A5':8, 'A6':6}
bank = {'10 yuan':10, '5 yuan':5, '2 yuan':2, '1 yuan':1}
A1 = Goods(name = 'A1', price = shelf['A1'])
A2 = Goods(name = 'A2', price = shelf['A2'])
A3 = Goods(name = 'A3', price = shelf['A3'])
A4 = Goods(name = 'A4', price = shelf['A4'])
A5 = Goods(name = 'A5', price = shelf['A5'])
A6 = Goods(name = 'A6', price = shelf['A6'])

C_10 = Cash(name = '10 yuan coin', denomination = 10)
C_5 = Cash(name = '5 yuan coin', denomination = 5)
C_2 = Cash(name = '2 yuan coin', denomination = 2)
C_1 = Cash(name = '1 yuan coin', denomination = 1)


Initialization = False
p_pay = 0
balance = 0
while True:
    try:
        code = input().strip().split(';')

        if code[-1] == '':
            code.pop()
        for c in code:
            #initialization
            if c[0] == 'r':
                r_good = c.split(' ')[1].split('-')
                r_cash = c.split(' ')[2].split('-')

                A1.set_count(int(r_good[0]))
                A2.set_count(int(r_good[1]))
                A3.set_count(int(r_good[2]))
                A4.set_count(int(r_good[3]))        
                A5.set_count(int(r_good[4]))
                A6.set_count(int(r_good[5]))    

                C_10.set_count(int(r_cash[0]))
                C_5.set_count(int(r_cash[1]))
                C_2.set_count(int(r_cash[2]))
                C_1.set_count(int(r_cash[3]))

                print('S001:Initialization is successful')

            #pay
            elif c[0] == 'p':
                p_pay = int(c.split(' ')[1])
                if p_pay not in [1,2,5,10]:
                    print('E002:Denomination error')
                elif p_pay > 10:
                    print('E004:Pay the balance is beyond the scope biggest')
                elif (C_1.denomination*C_1.count + C_2.denomination*C_2.count) < p_pay:
                    if p_pay in [5,10]:
                        print('E003:Change is not enough, pay fail')
                    elif p_pay in [1,2]:
                        if (A1.count + A2.count + A3.count + A4.count + A5.count + A6.count) ==0:
                            print('E005:All the goods sold out')
                        else:
                            balance = balance + p_pay
                            locals()['C_' + str(p_pay)].set_count(locals()['C_' + str(p_pay)].count + 1)
                            print('S002:Pay success,balance=',balance)
                else:
                    if (A1.count + A2.count + A3.count + A4.count + A5.count + A6.count) >0:
                        balance = balance + p_pay
                        locals()['C_' + str(p_pay)].set_count(locals()['C_' + str(p_pay)].count + 1)
                        print('S002:Pay success,balance=',balance)

            #buy
            elif c[0] == 'b':
                b_buy = c.split(' ')[1]
                if b_buy not in shelf.keys():
                    print('E006:Goods does not exist')
                    #break
                elif locals()[b_buy].count == 0:
                    print('E007:The goods sold out')

                elif balance < locals()[b_buy].price:
                    print('E008:Lack of balance')

                else:

                    balance = balance - locals()[b_buy].price
                    locals()[b_buy].set_count(locals()[b_buy].count - 1)

                    print('S003:Buy success,balance=',balance)

            #c 退币
            elif c[0] == 'c':
                c_cell = []
                bank_denomination = sorted(bank.items(),key = lambda item:item[1], reverse = True)
                for k in range(len(bank_denomination)):
                    c_num =  balance//(bank_denomination[k][1])
                    balance = balance%(bank_denomination[k][1])
                    c_cell.append(c_num)
                for l in range(len(bank_denomination)):
                    #locals()['C_' + str(bank_denomination[-1 - l][1])].set_count(locals()['C_' + str(bank_denomination[-1 - l][1])].count - c_cell[-1 - l])
                    locals()['C_' + str(bank_denomination[-1 - l][1])].set_count(locals()['C_' + str(bank_denomination[-1 - l][1])].count - c_cell[-1 - l]) 
                    print(bank_denomination[-1 - l][0] + ' coin number=' + str(c_cell[-1 - l]))

                balance = 0
                p_pay = 0

            #query
            elif c[0] == 'q':

                if ' ' not in c:
                    print('E010:Parameter error')
                    #break
                else:
                    q_category = c.split(' ')[1]
                    if q_category not in ['0','1']:
                        print('E010:Parameter error')
                        #break   

                    elif q_category == '0':
                        for g in range(6):
                            g_name = 'A'+str(g+1)
                            print(locals()[g_name].name + ' ' + str(locals()[g_name].price) + ' ' + str(locals()[g_name].count))
                    elif q_category == '1':
                        for g in range(4):
                            g_name = 'C_' + str(sorted(bank.items(), key = lambda item:item[1])[g][1])
                            print(locals()[g_name].name + ' number=' + str(locals()[g_name].count))

    except:
        break
发表于 2020-07-16 19:45:08 回复(1)
class sell:
    
    def __init__(self):
        self.A = None
        self.N_A = None
        self.money = None
        self.balance = 0
        
    def dostring(self,s):
        s = s.split(";")
        self.init(s[0])
        for i in range(1,len(s)):
            if len(s[i])>0:
                if s[i][0]=="p":self.OpPay(s[i])
                if s[i][0]=='b':self.OpBuy(s[i])
                if s[i][0]=='c':self.OpChange()
                if s[i][0]=='q':self.OpQuary(s[i])
        return
    
    def init(self,a):
        a = a.replace("-"," ")
        a = a.split()
        for i in range(len(a)):
            if a[i]=='r':
                self.A = {'A1':[2,int(a[i+1])],'A2':[3,int(a[i+2])],'A3':[4,int(a[i+3])],'A4':[5,int(a[i+4])],'A5':[8,int(a[i+5])],'A6':[6,int(a[i+6])]}
                self.N_A = [int(a[i+j]) for j in range(1,7)]
        self.money = {1:int(a[7]),2:int(a[8]),5:int(a[9]),10:int(a[10])}
        print("S001:Initialization is successful")
    
    def OpPay(self,temp):
        temp2 = temp.split(" ")
        p = int(temp2[1])
        if p not in [1,2,5,10]:
            print("E002:Denomination error")
            return
        M = 1 * self.money[1] + 2 * self.money[2]
        if (M < p)&(p not in [1,2]):
            print("E003:Change is not enough, pay fail")
            return
        if p>10:
            print("E004:Pay the balance is beyond the scope biggest")
            return
        if sum(self.N_A)==0:
            print("E005:All the goods sold out")
            return
        else:
            self.money[p] = self.money[p]+1
            self.balance = self.balance + p
            print("S002:Pay success,balance="+str(self.balance))
    
    def OpBuy(self,temp):
        temp2 = temp.split(" ")
        b = temp2[1]
        if b not in self.A:
            print("E006:Goods does not exist")
            return
        if self.A[b][1] == 0:
            print("E007:The goods sold out")
            return 
        if self.balance < self.A[b][0]:
            print("E008:Lack of balance")
            return        
        self.balance = self.balance-self.A[b][0]
        print("S003:Buy success,balance="+str(self.balance))
    
    def OpChange(self):
        c = self.balance
        if c == 0:
            print("E009:Work failure",end='')
        else:
            T = [0,0,0,0]
            while c > 0:
                if (c >= 10) & (self.money[10]>0):
                    T[3] = T[3]+1
                    c = c - 10
                    self.money[10] = self.money[10] - 1
                elif (c >= 5) & (self.money[5]>0):
                    T[2] = T[2]+1
                    c = c - 5
                    self.money[5] = self.money[5] - 1
                elif (c >= 2) & (self.money[2]>0):
                    T[1] = T[1]+1
                    c = c - 2
                    self.money[2] = self.money[2] - 1
                elif c > self.money[1]:
                    T[0] = T[0]+self.money[1]
                    self.money[1] = 0
                    c = 0
                else:
                    T[0] = T[0]+c
                    self.money[1] = self.money[1]-c
                    c = c - 1
            print("1 yuan coin number="+str(T[0]))
            print("2 yuan coin number="+str(T[1]))
            print("5 yuan coin number="+str(T[2]))
            print("10 yuan coin number="+str(T[3]))
            self.balance = 0
        
    def OpQuary(self,temp):
        if temp == 'q 0':
            for v in self.A:
                print(v+str(self.A[v][0])+str(self.A[v][1]))
        if temp == 'q 1':
            print("1 yuan coin number="+str(self.money[1]))
            print("2 yuan coin number="+str(self.money[2]))
            print("5 yuan coin number="+str(self.money[5]))
            print("10 yuan coin number="+str(self.money[10]))
        else:
            print("E010:Parameter error",end='')

if __name__ == '__main__':
    while True:
        try:
            S = sell()
            a = input()
            S.dostring(a)
        except:break

发表于 2020-06-15 20:50:06 回复(2)
//注意:1、E004:Pay the balance is beyond the scope biggest指的是投币错误,我之前看出了balance大于10报错,这样理解是错误的
//2、E009 和E10这两个输出后不要换行
//3、按照指示一点点敲代码吧,我写了300行,有点长,但是是自己一点点敲出来的,时间有限,我就懒得再简化了
#include<iostream>
#include<string>
#include<vector>
using namespace std;
vector<string> split(string str, const char c){
    vector<string> sstr;
    int pos = 0;
    while (pos < str.length()){
        int end;
        for (end = pos; (end < str.length())&&(str[end] != c); end++);
        sstr.push_back(str.substr(pos, end - pos));
        pos = end + 1;
    }
    return sstr;
}
void judgeInit(string init,vector<vector<int>>&inf){//info[0]记录商品数量,info[1]记录钱币数量
    vector<string> two_init = split(init, ' ');
    vector<string>first = split(two_init[0], '-');
    vector<string>second = split(two_init[1], '-');
    int i = 0;
    for (auto e : first){
        int n = atoi(e.c_str());
        inf[0][i++] = n;
    }
    i = 0;
    for (auto e : second){
        int n = atoi(e.c_str());
        inf[1][i++] = n;
    }
    cout << "S001:Initialization is successful" << endl;
}
bool goodsSoldOut(const vector<vector<int>>inf){
    for (int i = 0; i < 6; i++){
        if (inf[0][i] > 0){
            return false;
        }
    }
    return true;
}
void judgePay(int num, int &balance, vector<vector<int>>&inf){//num为硬币面值
    if (num != 1 && num != 2 && num != 5 && num != 10){
        cout << "E002:Denomination error" << endl;
        return;
    }
    else if (inf[1][0]+inf[1][1]*2 < num){
        cout << "E003:Change is not enough, pay fail" << endl;
        return;
    }
    else if (num > 10){//投币大于10元
        cout << "E004:Pay the balance is beyond the scope biggest" << endl;
        return;
    }
    else if (goodsSoldOut(inf)){
        cout << "E005:All the goods sold out" << endl;
        return;
    }
    else{
        switch (num){
        case 1:inf[1][0]++; balance += num; break;
        case 2:inf[1][1]++; balance += num; break;
        case 5:inf[1][2]++; balance += num; break;
        case 10:inf[1][3]++; balance += num; break;
        }
        cout << "S002:Pay success,balance=" << balance << endl;
        return;
    }
    
}
void judgeBuy(string good, int& balance, vector<vector<int>>&inf){
    //买商品,balance以及相应的商品数量会发生相应的变化。
    if (good != "A1" && good != "A2" && good != "A3" && good != "A4" && good != "A5" && good != "A6"){
        cout << "E006:Goods does not exist" << endl;
        return;
    }
    else if (good == "A1"){
        if (inf[0][0] == 0){//商品没了
            cout << "E007:The goods sold out" << endl;
        }
        else if (balance < 2){//钱不够了
            cout << "E008:Lack of balance" << endl;
        }
        else{//商品还有,钱也够,那就找零钱吧,所以要更新balance的数量,商品的数量,钱币的数量在退币的时候发生变化
            balance -= 2;
            inf[0][0]--;
            cout << "S003:Buy success,balance=" << balance << endl;
        }
        return;
    }
    else if (good == "A2"){
        if (inf[0][1] == 0){//商品没了
            cout << "E007:The goods sold out" << endl;
        }
        else if (balance < 3){//钱不够了
            cout << "E008:Lack of balance" << endl;
        }
        else{//商品还有,钱也够,那就找零钱吧,所以要更新balance的数量,商品的数量,钱币的数量在退币的时候发生变化
            balance -= 3;
            inf[0][1]--;
            cout << "S003:Buy success,balance=" << balance << endl;
        }
        return;
    }
    else if (good == "A3"){
        if (inf[0][2] == 0){//商品没了
            cout << "E007:The goods sold out" << endl;
        }
        else if (balance < 4){//钱不够了
            cout << "E008:Lack of balance" << endl;
        }
        else{//商品还有,钱也够,那就找零钱吧,所以要更新balance的数量,商品的数量,钱币的数量在退币的时候发生变化
            balance -= 4;
            inf[0][2]--;
            cout << "S003:Buy success,balance=" << balance << endl;
        }
        return;
    }
    else if (good == "A4"){
        if (inf[0][3] == 0){//商品没了
            cout << "E007:The goods sold out" << endl;
        }
        else if (balance < 5){//钱不够了
            cout << "E008:Lack of balance" << endl;
        }
        else{//商品还有,钱也够,那就找零钱吧,所以要更新balance的数量,商品的数量,钱币的数量在退币的时候发生变化
            balance -= 5;
            inf[0][3]--;
            cout << "S003:Buy success,balance=" << balance << endl;
        }
        return;
    }
    else if (good == "A5"){
        if (inf[0][4] == 0){//商品没了
            cout << "E007:The goods sold out" << endl;
        }
        else if (balance < 8){//钱不够了
            cout << "E008:Lack of balance" << endl;
        }
        else{//商品还有,钱也够,那就找零钱吧,所以要更新balance的数量,商品的数量,钱币的数量在退币的时候发生变化
            balance -= 8;
            inf[0][4]--;
            cout << "S003:Buy success,balance=" << balance << endl;
        }
        return;
    }
    else if (good == "A6"){
        if (inf[0][5] == 0){//商品没了
            cout << "E007:The goods sold out" << endl;
        }
        else if (balance < 6){//钱不够了
            cout << "E008:Lack of balance" << endl;
        }
        else{//商品还有,钱也够,那就找零钱吧,所以要更新balance的数量,商品的数量,钱币的数量在退币的时候发生变化
            balance -= 6;
            inf[0][5]--;
            cout << "S003:Buy success,balance=" << balance << endl;
        }
        return;
    }
}
void refound(int&balance, vector<vector<int>>&inf){
    if (balance <= 0){
        cout << "E009:Work failure";//注意这里不用换行
        return;
    }
    else{
        int a10 = 0,a5=0,a2=0,a1=0;
        while (balance>0){
            if (balance >= 10){
                if (inf[1][3] > 0){
                    inf[1][3]--;
                    balance -= 10;
                    a10++;
                }
                else if (inf[0][2] > 0){
                    inf[1][2]--;
                    balance -= 5;
                    a5++;
                }
                else if (inf[1][1] > 0){
                    inf[1][1]--;
                    balance -= 2;
                    a2++;
                }
                else if (inf[0][0] > 0){
                    inf[1][0]--;
                    balance -= 1;
                    a1++;
                }
                else{
                    balance = 0;
                    break;
                }
            }
            else if(balance>=5){
                if (inf[1][2] > 0){//先判断有没有5元硬币
                    inf[1][2]--;
                    balance -= 5;
                    a5++;
                }
                else if (inf[0][1] > 0){//再判断有没有2元硬币
                    inf[1][1]--;
                    balance -= 2;
                    a2++;
                }
                else if (inf[1][0] > 0){//再判断有没有1元硬币
                    inf[1][0]--;
                    balance -= 1;
                    a1++;
                }
                else{//再判断是否终止退币
                    balance = 0;
                    break;
                }
            }
            else if (balance >= 2){
                if (inf[1][1] > 0){//再判断有没有2元硬币
                    inf[1][1]--;
                    balance -= 2;
                    a2++;
                }
                else if (inf[1][0] > 0){//再判断有没有1元硬币
                    inf[1][0]--;
                    balance -= 1;
                    a1++;
                }
                else{//再判断是否终止退币
                    balance = 0;
                    break;
                }
            }
            else{//balance >= 1
                if (inf[1][0] > 0){//再判断有没有1元硬币
                    inf[1][0]--;
                    balance -= 1;
                    a1++;
                }
                else{//再判断是否终止退币
                    balance = 0;
                    break;
                }
            }
        }
        cout << "1 yuan coin number=" <<a1<< endl;
        cout << "2 yuan coin number=" <<a2<< endl;
        cout << "5 yuan coin number=" <<a5<< endl;
        cout << "10 yuan coin number=" <<a10<< endl;
    }
}
void query(string flag, vector<vector<int>>&inf){
    if (flag == "0"){
        cout << "A1 2 " << inf[0][0] << endl;
        cout << "A2 3 " << inf[0][1] << endl;
        cout << "A3 4 " << inf[0][2] << endl;
        cout << "A4 5 " << inf[0][3] << endl;
        cout << "A5 8 " << inf[0][4] << endl;
        cout << "A6 6 " << inf[0][5] << endl;
    }
    else if (flag == "1"){
        cout << "1 yuan coin number=" << inf[1][0] << endl;
        cout << "2 yuan coin number=" << inf[1][1] << endl;
        cout << "5 yuan coin number=" << inf[1][2] << endl;
        cout << "10 yuan coin number=" << inf[1][3] << endl;
    }
    else{
        cout << "E010:Parameter error";//注意这个输出不用换行
    }
}
int main(){
    string inputs;
    while (getline(cin, inputs)){
        vector<string>ss1 = split(inputs, ';');
        vector<vector<int>>info(2,vector<int>(6,0));//info[0]存储A1-A6的饮料数量,info[1]存储1,2,5,10元纸币的数量
        int balance = 0;
        for (auto e : ss1){
            if (e[0] == 'r'){//初始化
                judgeInit(e.substr(2), info);//初始化成功    
            }
            else if (e[0] == 'p'){//投入钱币,注意balance和info[1]会因为投币而发生相应变化
                int pay = atoi(e.substr(2).c_str());
                judgePay(pay, balance, info);
            }
            else if (e[0] == 'b'){//买物品
                string good = e.substr(2);
                judgeBuy(good, balance, info);
            }
            else if (e[0] == 'c'){//退钱
                refound(balance, info);
            }
            else if (e[0] == 'q'){//查询商品
                query(e.substr(2), info);
            }
            
        }
        
    }
    return 0;
}

编辑于 2019-07-23 15:58:22 回复(0)

这是为什么?
发表于 2017-02-10 16:47:27 回复(2)
题目太长,不想做
发表于 2020-02-22 15:23:29 回复(42)

这个系统功能完全写出来就可以直接卖钱了好么,出题人/公司的意图...

发表于 2018-01-16 16:36:47 回复(7)

import java.util.Scanner;

/**
 * 自动售货系统
 * @author Administrator
 *
 */
public class Main{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			String s = sc.nextLine();
			doString(s);
		}
		sc.close();
	}
	public static void doString(String input){
		String[] arr = input.split(";");
		String initial = arr[0];
		Goods goods = OpReset(initial);
		for(int i=1;i<arr.length;i++){
			String temp = arr[i];
			String[] temp2 = temp.split(" ");
			if(temp2[0].equals("p")){
				goods = OpPay(temp,goods);
			}else if(temp2[0].equals("b")){
				goods = OpBuy(temp,goods);
			}else if(temp2[0].equals("c")){
				goods = OpChange(temp,goods);
			}else if(temp2[0].equals("q")||temp2[0].matches("q\\d")){
				OpQuery(temp,goods);
			}
			
		}

	}
	public static Goods OpReset(String initial){//初始化
		String[] arr = initial.split(" ");
		String[] Asome = arr[1].split("-");
		String[] Moneysome = arr[2].split("-");
		int[] A = new int[Asome.length];
		int[] B = new int[Moneysome.length];
		for(int i=0;i<Asome.length;i++){
			A[i]=Integer.valueOf(Asome[i]);
		}
		for(int i=0;i<Moneysome.length;i++){
			B[i]=Integer.valueOf(Moneysome[i]);
		}
		Goods goods = new Goods(A,B,0);
		System.out.println("S001:Initialization is successful");
		return goods;
	}
	public static Goods OpPay(String payString,Goods goods){//投币
		String[] arr = payString.split(" ");
		int payNum = Integer.valueOf(arr[1]);
		if(payNum!=1&&payNum!=2&&payNum!=5&&payNum!=10){
			System.out.println("E002:Denomination error");
			return goods;
		}
		else if((payNum==5||payNum==10)&&(goods.num_coin[0]*1+goods.num_coin[1]*2<payNum)){
			System.out.println("E003:Change is not enough, pay fail");
			return goods;
		}
		else if(payNum>10){
			System.out.println("E004:Pay the balance is beyond the scope biggest");
			return goods;
		}
		else if(goods.num_goods[0]==0&&goods.num_goods[1]==0&&goods.num_goods[2]==0&&goods.num_goods[3]==0&&goods.num_goods[4]==0&&goods.num_goods[5]==0){
			System.out.println("E005:All the goods sold out");
			return goods;
		}
		else{
			switch(payNum){
			case 1:goods.num_coin[0]++;break;
			case 2:goods.num_coin[1]++;break;
			case 5:goods.num_coin[2]++;break;
			case 10:goods.num_coin[3]++;break;
			}
			int tmp = payNum + goods.toubi_yu_e;
			goods.toubi_yu_e += payNum;
			System.out.println("S002:Pay success,balance="+tmp);
			return goods;
		}
		
	}
	public static Goods OpBuy(String buyString,Goods goods){//购买商品
		String[] goodsString = {"A1","A2","A3","A4","A5","A6"};
		String[] arr = buyString.split(" ");
		String buy = arr[1];
		int price = 0;
		int index = 10;
		for(int i=0;i<goodsString.length;i++){
			if(buy.equals(goodsString[i])){
				switch(i){
				case 0:price = 2;index=i;break;
				case 1:price = 3;index=i;break;
				case 2:price = 4;index=i;break;
				case 3:price = 5;index=i;break;
				case 4:price = 8;index=i;break;
				case 5:price = 6;index=i;break;
				}

			}
		}
		if(index==10){
			System.out.println("E006:Goods does not exist");
			return goods;
		}
		else if(goods.toubi_yu_e<price){
			System.out.println("E008:Lack of balance");
			return goods;
		}
		else if(goods.num_goods[index]==0){
			System.out.println("E007:The goods sold out");
			return goods;
		}
		else{
			goods.toubi_yu_e=goods.toubi_yu_e-price;
			System.out.println("S003:Buy success,balance="+goods.toubi_yu_e);
			return goods;
		}
	}
	public static Goods OpChange(String changeString,Goods goods){//退币
		if(goods.toubi_yu_e==0){
			System.out.print("E009:Work failure");
			return goods;
		}else{
			int tuibi = goods.toubi_yu_e;
			int num_shi = tuibi/10;

			if(goods.num_coin[3]-num_shi<0){
				num_shi = goods.num_coin[3];
			}
			int num_wu = (tuibi-10*num_shi)/5;
			if(goods.num_coin[2]-num_wu<0){
				num_wu = goods.num_coin[2];
			}
			int num_er = (tuibi-10*num_shi-5*num_wu)/2;
			if(goods.num_coin[1]-num_er<0){
				num_er = goods.num_coin[1];
			}
			int num_yi = (tuibi-10*num_shi-5*num_wu-2*num_er)/1;
			if(goods.num_coin[0]-num_yi<0){
				num_yi = goods.num_coin[0];
			}
			goods.num_coin[3] = goods.num_coin[3]-num_shi;
			goods.num_coin[0] = goods.num_coin[0]-num_yi;
			goods.num_coin[1] = goods.num_coin[1]-num_er;
			goods.num_coin[2] = goods.num_coin[2]-num_wu;
	
			goods.toubi_yu_e=0;
			System.out.println("1 yuan coin number="+num_yi);
			System.out.println("2 yuan coin number="+num_er);
			System.out.println("5 yuan coin number="+num_wu);
			System.out.println("10 yuan coin number="+num_shi);
			return goods;
		}
	}
	public static void OpQuery(String queryString,Goods goods){
		String[] arr = queryString.split(" ");
		String query = "";
		if(arr.length==2){
			query = arr[1];
		}
		else{
			System.out.print("E010:Parameter error");
		}
		if(query.equals("0")){
			System.out.println("A1 "+"2 "+goods.num_goods[0]);
			System.out.println("A2 "+"3 "+goods.num_goods[1]);
			System.out.println("A3 "+"4 "+goods.num_goods[2]);
			System.out.println("A4 "+"5 "+goods.num_goods[3]);
			System.out.println("A5 "+"6 "+goods.num_goods[4]);
			System.out.println("A6 "+"7 "+goods.num_goods[5]);
		}else if(query.equals("1")){
			System.out.println("1 yuan coin number="+goods.num_coin[0]);
			System.out.println("2 yuan coin number="+goods.num_coin[1]);
			System.out.println("5 yuan coin number="+goods.num_coin[2]);
			System.out.println("10 yuan coin number="+goods.num_coin[3]);
		}
	}
}
class Goods{
	int[] num_goods = new int[6];
	int[] num_coin = new int[4];
	int toubi_yu_e;
	public Goods(int[] num_goods,int[] num_coin,int toubi_yu_e){
		this.num_goods = num_goods;
		this.num_coin = num_coin;
		this.toubi_yu_e = toubi_yu_e;
	}

}

1  总体说明 
考生需要模拟实现一个简单的自动售货系统,实现投币、购买商品、退币、查询库存商品及存钱盒信息的功能。
系统初始化时自动售货机中商品为6种商品,商品的单价参见1.1规格说明,存钱盒内放置1元、2元、5元、10元钱币,商品数量和钱币张数通过初始化命令设置,参见2.1 系统初始化。
1.1 规格说明
1. 商品:每种商品包含商品名称、单价、数量三种属性,其中商品名不重复。考生不能修改商品名称和单价,初始化命令设置商品数量。这些信息在考试框架中进行定义,考生在实现功能代码时可直接使用。
商品 名称
单价
数量
A1 2 X
A2 3 X
A3 4 X
A4 5 X
A5 8 X
A6 6 X
2. 存钱盒信息:钱币面额、张数两种属性。初始化命令设置各种面额钱币张数。这些信息在考试框架中进行定义,考生在实现功能代码时可直接使用。
钱币面额
张数
10元
X
5元
X
2元 X
1元 X
3. 退币原则
1) 根据系统存钱盒内钱币的 信息 ,按钱币总张数最少的原则进行退币。
2) 如果因零钱不足导致不能退币,则尽最大可能退币,以减少用户损失。
例如:假设存钱盒内只有4张2元,无其它面额钱币。如果需要退币7元,系统因零钱不足无法退币,则继续尝试退币6元,最终系统成功退币3张2元,用户损失1元钱币。
4. 投币操作说明:每次投币成功,投入的钱币面额累加到投币余额;同时,本次投入的钱币放入存钱盒中,存钱盒相应面额钱币增加。
5. 投币余额:指当前自动售货机中用户剩余的可购买商品的钱币总额;例如:投入2元面额的钱币,投币余额增加2元;购买一件价格2元的商品,投币余额减少2元;
6. 投币余额约束:投币余额不能超过10元。
7. 退币操作说明:退币操作需要遵守 退币原则 ;退币成功后,投币余额清零,同时扣除存钱盒相应的金额。
8. 购买商品操作说明:一次仅允许购买一件商品;购买商品成功后,自动售货机中对应商品数量减1,投币余额扣除本次购买商品的价格。
2 操作说明
命令字与第一个参数间使用一个空格分隔,多条命令采用分号隔开。考试系统会对输入命令格式进行处理,考生不需要关注输入命令格式的合法性,只需要实现命令处理函数。
2.1 系统初始化
命令格式
r A1 数量 -A2 数量 -A3 数量 -A4 数量 -A5 数量 -A6 数量 1 元张数 -2 元张数 -5 元张数 -10 元张数
参数名称
参数说明
类型
取值范围
A1数量
商品A1数量
整数
[0,10]
A2数量
商品A2数量
整数
[0,10]
A3数量
商品A3数量
整数
[0,10]
A4数量
商品A4数量
整数
[0,10]
A5数量
商品A5数量
整数
[0,10]
A6数量
商品A6数量
整数
[0,10]
1元张数
面额1元钱币张数
整数
[0,10]
2元张数
面额2元钱币张数
整数
[0,10]
5元张数
面额5元钱币张数
整数
[0,10]
10元张数
面额10元钱币张数
整数
[0,10]
商品和各种面额钱币取值范围只是作为初始化命令的限制,其它场景下不限制取值范围;考试框架已经实现取值范围的检查,考生不需要关注。
功能说明:设置自动售货机中商品数量和存钱盒各种面额的钱币张数;
约束说明:系统在任意阶段均可执行r初始化系统;考生不需要关注参数的合法性,不需要关注增加或缺少参数的场景;
输出说明:输出操作成功提示(执行完r命令后系统会自动输出操作结果,考生不需要再次调用输出函数),例:
命令 输出 含义
r 6-5-4-3-2-1 4-3-2-1; S001:Initialization is successful 初始化成功
2.2 投币
命令格式p 钱币面额
功能说明
(1) 如果投入非1元、2元、5元、10元的钱币面额(钱币面额不考虑负数、字符等非正整数的情况),输出“E002:Denomination error”;
(2) 如果存钱盒中1元和2元面额钱币总额小于本次投入的钱币面额,输出“E003:Change is not enough, pay fail”,但投入1元和2元面额钱币不受此限制。
(3) 如果投币余额大于10元,输出“E004:Pay the balance is beyond the scope biggest”;
(4) 如果自动售货机中商品全部销售完毕,投币失败。输出“E005:All the goods sold out”;
(5) 如果投币成功,输出“S002:Pay success,balance=X”;
约束说明
(1) 系统在任意阶段都可以投币;
(2) 一次投币只能投一张钱币;
(3) 同等条件下,错误码的优先级:E002 > E003 > E004 > E005;
输出说明:如果投币成功,输出“S002:Pay success,balance=X”。
例:
命令
输出
p 10;
S002:Pay success,balance=10
2.3 购买商品
命令格式b 商品名称
功能说明
(1) 如果购买的商品不在商品列表中,输出“E006:Goods does not exist”;
(2) 如果所购买的商品的数量为0,输出“E007:The goods sold out”;
(3) 如果投币余额小于待购买商品价格,输出“E008:Lack of balance”;
(4) 如果购买成功,输出“S003:Buy success,balance=X”;
约束说明
(1) 一次购买操作仅能购买一件商品,可以多次购买;
(2) 同等条件下,错误码的优先级:E006 > E007 > E008;
输出说明:
如果购买成功,输出“S003:Buy success,balance=X”。
例:
命令
输出
b A1;
S003:Buy success,balance=8
2.4 退币
命令格式c
功能说明
(1) 如果投币余额等于0的情况下,输出“E009:Work failure”;
(2) 如果投币余额大于0的情况下,按照 退币原则 进行“找零”,输出退币信息;
约束说明
(1) 系统在任意阶段都可以退币;
(2) 退币方式必须按照 退币原则 进行退币;
输出说明:如果退币成功,按照 退币原则 输出退币信息。
例,退5元钱币:
命令
输出
c;
1 yuan coin number=0
2 yuan coin number=0
5 yuan coin number=1
10 yuan coin number=0
2.5 查询
命令格式q 查询类别
功能说明
(1) 查询自动售货机中商品信息,包含商品名称、单价、数量。 根据商品数量从大到小进行排序;商品数量相同时,按照商品名称的先后顺序进行排序
例如:A1的商品名称先于A2的商品名称,A2的商品名称先于A3的商品名称。
(2) 查询存钱盒信息,包含各种面额钱币的张数;
(3) 查询类别如下表所示:
查询类别
查询内容
0
查询商品信息
1 查询存钱盒信息
如果“查询类别”参数错误,输出“E010:Parameter error”。“查询类别”参数错误时,不进行下面的处理;
输出说明
“查询类别”为0时,输出自动售货机中所有商品信息(商品名称单价数量)例:
命令
输出
q 0;
A1 2 6
A2 3 5
A3 4 4
A4 5 3
A5 8 2
A6 6 0
“查询类别”为1时,输出存钱盒信息(各种面额钱币的张数),格式固定。例:
命令
输出
q 1;
1 yuan coin number=4
2 yuan coin number=3
5 yuan coin number=2
10 yuan coin number=1

编辑于 2017-08-10 17:24:53 回复(4)
做这道题都是真的勇士🤣
发表于 2020-04-25 02:14:10 回复(0)
总结一下!测试用例就是坑:
1:说好只是参数不对,q指令,会出现没有空格消失,指令格式不对的情况:
2:退币算法说的根本不清楚
3:还有E009,E010都没有回行,
4:根本没有他说的balance不能大于10的限制
编辑于 2020-03-30 01:47:02 回复(0)
题目的字数,我直接下一题
发表于 2021-09-01 14:04:36 回复(0)

考察知识点:这道题除了测试集E010和E009后面没有回车之外(疯狂吐槽),唯一值得注意的是退币算法。

本题涉及到两个算法:一、足够时,尽最大可能退纸张数最少的钱。二、不足时,尽最大可能退最多的钱。

一:足够时,尽最大可能退纸张数最少的钱

我使用了贪心算法,在当前剩余的储钱箱中找最大且小于剩余未付金钱的纸币。

例如:未付钱币:9元,应该先找5元,如果没有5元,则找2元。依次类推。

但是按照这种方案找钱,可能出现找不开的情况。

例如:
现有钱币:

1元 2元 5元 10元
0张 3张 1张 0张

需要退出6元时,应该退2元,而不是5元。所以要在选择每一步后判断是否成功。

int moneyNumber[4] = {1, 2, 5, 10};
//current储钱箱里钱的数量,大小为4,分别表示 1 2 5 10元。
//例如{1,1,1,1} 1 2 5 10元 都有一张
bool enough(vector<int>& current, int money){
    if(money == 0)return true;//需要找的钱为0时,成功。
    for(int i = current.size()-1 ; i >= 0 ; --i){
        if(current[i] > 0 && money >= moneyNumber[i]){
            current[i]--;//先把最大的钱给你。
            if(enough(current, money-moneyNumber[i]))
                return true;//如果下一步成功了,则这一步也成功。
            else
                current[i]++;//当前选择不成功,则需要把钱拿回来。
        }
    }
    return false;//我这里的钱都少于需要找的钱
}

二、不足时,尽最大可能退最多的钱

直接从储钱箱中拿出最大的,且小于剩余钱币的。

int moneyNumber[4] = {1, 2, 5, 10};
//current储钱箱里钱的数量,大小为4,分别表示 1 2 5 10元。
//例如{1,1,1,1} 1 2 5 10元 都有一张
void bestCallback(vector<int>& current, int money){
    for(int i = current.size()-1 ; i >= 0 ; --i){
        while(current[i] > 0 && money >= moneyNumber[i]){
            current[i]--;
            money -= moneyNumber[i];
        }
    }
}
发表于 2019-03-13 15:59:06 回复(3)
/*
    这道题没有什么难点,但是很麻烦,将每部分功能化成子模块实现会比较简单;
    注意测试用例中E009和E010输出不需要换行,而且报错不太靠谱;
    每次初始化时将用户金额等参数初始设置即可,附AC代码;
/*
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <stdlib.h>
using namespace std;
vector<int> pt1={0,0,0,0,0,0},pt2={2,3,4,5,8,6};
vector<vector<int>> goods;//商品数量及价格
vector<int> coin={0,0,0,0};//一元,两元,五元,十元零钱数量
vector<int> yuan={1,2,5,10};
int pay=0;//投币金额
bool Initialization(string comd)
{
    char c;
    int i,j;
    pay=0;
    j=comd.find(';');
    comd=comd.substr(2,j-2);
    j=comd.find(' ');
    string s1,s2;
    s1=comd.substr(0,j);
    s2=comd.substr(j+1);
    for(i=0,j=0;i<s1.size();i++)
    {
        if(isdigit(s1[i]))
        {
            if(i+1<s1.size() && isdigit(s1[i+1]))
            {
                string temp=s1.substr(i,2);
                goods[0][j]=atoi(temp.c_str());
                j++;
                i++;
            }else{
                goods[0][j]=s1[i]-48;
                j++;
            }
        }
    }
    for(i=0,j=0;i<s2.size();i++)
    {
        if(isdigit(s2[i]))
        {
            if(i+1<s2.size() && isdigit(s2[i+1]))
            {
                string temp=s2.substr(i,2);
                coin[j]=atoi(temp.c_str());
                j++;
                i++;
            }else{
                coin[j]=s2[i]-48;
                j++;
            }
        }
    }
    cout<<"S001:Initialization is successful"<<endl;
    return true;
}
int CheckPay(string comd)
{
    int p1,j;
    j=comd.find(';');
    comd=comd.substr(2,j-2);
    p1=atoi(comd.c_str());
    if(p1!=1 && p1!=2 && p1!=5 && p1!=10)
    {
        cout<<"E002:Denomination error"<<endl;
        return -2;
    }else if(p1 > coin[0]+2*coin[1])
    {
        cout<<"E003:Change is not enough, pay fail"<<endl;
        return -3;
    }else if(p1>10)
    {
        cout<<"E004:Pay the balance is beyond the scope biggest"<<endl;
        return -4;
    }else if(accumulate(goods[0].begin(),goods[0].end(),0)==0)
    {
        cout<<"E005:All the goods sold out"<<endl;
        return -5;
    }else
    {
        pay+=p1;
        cout<<"S002:Pay success,balance="<<pay<<endl;//当前金额?总金额?
        if(p1==1) coin[0]++;
        else if(p1==2) coin[1]++;
        else if(p1==5) coin[2]++;
        else if(p1==10) coin[3]++;
        return 1;
    }
}
int Buy(string comd)
{
    int j;
    j=comd.find(';');
    string name=comd.substr(2,j-2);
    if(name!="A1" && name!="A2" && name!="A3" && name!="A4" && name!="A5" && name!="A6")
    {
        cout<<"E006:Goods does not exist"<<endl;
        return -6;
    }
    if(goods[0][name[1]-49]==0)
    {
        cout<<"E007:The goods sold out"<<endl;
        return -7;
    }
    if(goods[1][name[1]-49]>pay)
    {
        cout<<"E008:Lack of balance"<<endl;
        return -8;
    }
    pay-=goods[1][name[1]-49];
    goods[0][name[1]-49]--;
    cout<<"S003:Buy success,balance="<<pay<<endl;
    return 1;
}
bool CoinReturn()
{
    vector<int> ret={0,0,0,0};
    if(pay==0)
    {
        cout<<"E009:Work failure";
        return false;
    }
    int i;
    for(i=3;pay!=0 && i>=0; )
    {
        if(pay>=yuan[i] && coin[i]>0)
        {
            pay-=yuan[i];
            coin[i]--;
            ret[i]++;
        }else i--;
    }
    for(i=0;i<4;i++)
        cout<<yuan[i]<<" yuan coin number="<<ret[i]<<endl;
    return true;
}
void Query(string comd)
{
    int num,i;
    i=comd.find(';');
    comd=comd.substr(2,i-2);
    if(comd.size()!=1)
        num=-1;
    else
        num=comd[0]-48;
    if(num==0)
        for(i=0;i<6;i++)
            cout<<'A'<<i+1<<' '<<goods[1][i]<<' '<<goods[0][i]<<endl;
    else if(num==1)
        for(i=0;i<4;i++)
            cout<<yuan[i]<<" yuan coin number="<<coin[i]<<endl;
    else
        cout<<"E010:Parameter error";
}
int main()
{
    string command;
    goods.push_back(pt1);goods.push_back(pt2);
    while(getline(cin,command))
    {
        for(int i=0;i<command.size();i++)
        {
            if(command[i]=='r') Initialization(command.substr(i));
            else if(command[i]=='p') CheckPay(command.substr(i));
            else if(command[i]=='b') Buy(command.substr(i));
            else if(command[i]=='c') CoinReturn();
            else if(command[i]=='q') Query(command.substr(i));
        }
    }
    return 0;
}

发表于 2018-08-19 18:55:13 回复(1)
这也太长了吧,不想做了..........
发表于 2020-08-01 16:46:15 回复(1)

问题信息

难度:
126条回答 25286浏览

热门推荐

通过挑战的用户

查看代码