题目分析
数据结构选择
题目提示的已经非常明显了,FIFO裸题,无脑选队列就对了。队列中存储的每个元素为二元组 ,其中 为该批次鸡蛋的采购日期, 为该批次剩余的鸡蛋数量。
核心思路
世界上只有两种算法,一种叫枚举,一种叫模拟。
而这个题显然不能枚举,所以模拟就好了。
直接模拟餐厅每日的三个核心操作,利用队列的先进先出特性保证鸡蛋的使用顺序,同时在每日操作的最后清理过期鸡蛋。
操作步骤
- 将当日采购的鸡蛋作为新批次加入队列尾部;
- 从队头弹出,若队首批次的鸡蛋数不足则弹出该批次,否则扣减对应数量;
- 从队头检查,若批次的采购日期满足 (入话:存放天数 ),则弹出该批次,直到队首无过期鸡蛋。
最终统计队列中所有批次的剩余鸡蛋数之和,即为答案。
代码
#include<bits/stdc++.h>
using namespace std;
constexpr int N = 2e5 + 5;
int n, d;
int a[N], b[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
cin >> n >> d;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= n; ++i) cin >> b[i];
queue<pair<int, int>> q;
for (int i = 1; i <= n; ++i) {
q.emplace(i, a[i]);
int need = b[i];
while (need > 0) {
auto cur = q.front();
int cnt = cur.second;
if (cnt > need) {
cur.second -= need;
need = 0;
} else {
need -= cnt;
q.pop();
}
}
while (!q.empty()) {
int day = q.front().first;
if (day <= i - d) {
q.pop();
} else {
break;
}
}
}
int res = 0;
while (!q.empty()) {
res += q.front().second;
q.pop();
}
cout << res << '\n';
}
return 0;
}