L2-4 彩虹瓶 (25分) 栈的运用

 代码虽然写的有点乱,但是还是过了哈哈。

主要就是模拟题目那个意思,仔细点就好了。

#include <iostream>
#include <malloc.h>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <cstring>
#define IO                       \
    ios::sync_with_stdio(false); \
    cin.tie(0);                  \
    cout.tie(0);
using namespace std;
typedef long long LL;
int dis[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
const int maxn = 500000 + 10;
// const LL mod = 998244353;
const int inf = 0x3f3f3f3f;
int a[maxn];
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    IO;
    int n, m, k;
    cin >> n >> m >> k;
    while (k--)
    {
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        int flag = 0;
        stack<int> s1; // 货柜序列
        stack<int> s;  // 瓶子
        int i = 1;     //  指向货物序列
        int p = 1;     // 表示当前应该放进的 序号
        while (p <= n)
        {
            if (i <= n)
            {
                if (a[i] == p) // 若当前颜色可以直接放入瓶子那么 放进去
                {
                    ++p;
                    ++i;
                }
            }
            if (!s1.empty() && s1.top() == p)
            {
                s1.pop(); // 临时货架栈顶可以直接放到瓶子里
                ++p;
            }
            else if (!s1.empty() && s1.top() != p && i == n + 1)
            {
                flag = 1; // 货物已经运输完毕 但是 临时货架上栈顶并不能放到瓶子里
                break;
            }
            else if (i <= n)
            {
                if (a[i] == p) // 可能会出现先把临时货架上的拿下才能将货物序列送来的放入瓶子
                {              // 这个地方 一开始忘了
                    ++p;
                    ++i;
                }
                else
                {
                    s1.push(a[i]); // 送来的放不进去瓶子 那么放到临时货架上
                    ++i;
                }
                if (s1.size() > m) // 超出临时货架容量
                {
                    flag = 1;
                    break;
                }
            }
        }
        if (flag)
            cout << "NO" << endl;
        else
            cout << "YES" << endl;
    }
    return 0;
}
发布了81 篇原创文章 · 获赞 29 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/104319985