洛谷:P5661
OJ:P4963
解题思路:
我们需要模拟小轩的乘车过程,按照时间顺序处理每一条乘车记录,并根据优惠方案计算总花费。关键在于如何管理和使用地铁乘坐后获得的优惠票,以及如何在乘坐公交车时正确地应用这些优惠票。
算法步骤:
deque)来存储优惠票,每张优惠票包含两个信息:地铁乘车开始时间(t_subway)和地铁票价(price_subway)。type == 0):
totalCost += price)。type == 1):
price <= it->price)。time - it->time <= 45)。discountTickets.erase(it))。totalCost += price)。详细解释:
Ticket 来表示优惠票,包含地铁乘车开始时间 time 和地铁票价 price。deque<Ticket> discountTickets 来存储所有未使用且未过期的优惠票。totalCost 中。discountTickets 队列的尾部。while 循环,从队列的前端开始,检查优惠票是否已过期(time - discountTickets.front().time > 45)。pop_front() 将其从队列中移除。for 循环,从队列的前端开始遍历所有未过期的优惠票。price <= it->price)。time - it->time <= 45)。erase(it) 将其从队列中移除。usedTicket = true,表示已使用优惠票。break 跳出循环,避免继续遍历后续的优惠票。usedTicket == true),则不需要将公交车票价加到 totalCost 中。totalCost 中。算法复杂度分析:
注意事项:
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | /**************************************************************** * Description: 2019年普及组第二题 公交换乘 * Author: Alex Li * Date: 2024-09-24 14:56:22 * LastEditTime: 2024-09-24 18:19:29 ****************************************************************/ #include <iostream> #include <deque> using namespace std; struct Ticket { int time; // 地铁乘车开始时间 t_subway int price; // 地铁票价 price_subway }; int main() { int n; cin >> n; deque<Ticket> discountTickets; // 存储优惠票 int totalCost = 0; // 总花费 for (int i = 0; i < n; ++i) { int type, price, time; cin >> type >> price >> time; if (type == 0) { // 地铁乘坐 totalCost += price; discountTickets.push_back({time, price}); } else { // 公交车乘坐 // 移除过期的优惠票 while (!discountTickets.empty() && time - discountTickets.front().time > 45) { discountTickets.pop_front(); } // 查找可用的优惠票 bool usedTicket = false; for (auto it = discountTickets.begin(); it != discountTickets.end(); ++it) { if (price <= it->price && time - it->time <= 45) { // 使用这张优惠票 discountTickets.erase(it); usedTicket = true; break; } } if (!usedTicket) { // 支付公交车票价 totalCost += price; } } } cout << totalCost << endl; return 0; } |