L2-032 彩虹瓶 (25 分)
L2-032 彩虹瓶 (25 分)
这道题可以说是个模拟题,用栈来模拟货架,每次取货物时,先访问下栈顶是否有合适的货物,不合适,就再搬来一件,不符合就加到栈中,详细解释看代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <queue>
#include <stack>
#include <set>
#include <unordered_set>
using namespace std;
int n, m, k; //颜色的数量,货架的容量,需要判断发货顺序的数量
int main()
{
cin >> n >> m >> k;
while (k--)
{
vector<int> v(n);
stack<int> st;
st.push(0); //避免越界访问
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
int ans = 1;
bool flag = true;
int i = 0;
while (i < n)
{
if (ans != st.top()) //如果货架上没有匹配的货
{
if (ans != v[i]) //如果搬来的货物仍不匹配
{
st.push(v[i]); //把货物加到架子上
if (st.size() - 1 > m) //如果架子容不下货物
{
flag = false;
break;
}
}
else //如果搬来的货物匹配
ans++;
i++; //准备匹配下一个
}
else //如果架子上货物匹配
{
ans++;
st.pop(); //弹出货物
}
}
while (st.size() != 1 && flag) // 当货物全部被搬到架子上,判断架子上的货物是否都匹配
{
if (ans == st.top())
{
ans++;
st.pop();
}
else
{
flag = false;
break;
}
}
if (flag)
cout << "YES" << endl;
else
cout << "NO" << endl;
}