【出分前夕】遵循题目的bug解题:只要船租过一次,就可以一直还,不用考虑船的状态,因此暂时不出栈
#include <cstdio> #include <string> #include <vector> #include <stack> #include <cmath> using namespace std; // 将时间字符串转换为分钟数 int timeToMinutes(const string& time) { int hour = stoi(time.substr(0, 2)); int minute = stoi(time.substr(3, 2)); return hour * 60 + minute; } int main() { int num; // 船号 char oper; // 租船S(入栈),借船E(出栈) char time[20]; // 起始时间 vector<stack<string>> boats(101); // 每个元素是一个栈,下标是船号(1~100),对应栈中存储该船开始时间 int cnt = 0; double total_time = 0; // 租船次数和总时间 while (scanf("%d %c%s", &num, &oper, time) != EOF) { if (num == -1) { break; // 输入结束 } if (num == 0) { // 输入了0,输出当天的租船次数和平均租船时间 if (cnt == 0) { printf("0 0\n"); // 如果没有租船记录,输出0 0 } else { printf("%d %.0f\n", cnt, total_time / cnt); } // 重置数据,清空栈,为下一次输入做准备 cnt = 0; total_time = 0; for (int i = 0; i < 101; i++) { while (!boats[i].empty()) { boats[i].pop(); } } } if (oper == 'S') { // 租船操作,压栈 boats[num].push(time); } else if (oper == 'E') { // 还船操作,弹栈并计算时间 if (!boats[num].empty()) { string start_time = boats[num].top(); // 只要船租过一次,就可以一直还,不用考虑船的状态,因此暂时不出栈 // boats[num].pop(); int start_minutes = timeToMinutes(start_time); int end_minutes = timeToMinutes(time); int duration = end_minutes - start_minutes; total_time += duration; cnt++; // 成功还船,租船次数加1 } // 如果栈为空,忽略此次还船操作,不做任何操作 } } return 0; }