1. 程式人生 > 其它 >2020-12-28 出棧序列的合法性

2020-12-28 出棧序列的合法性

技術標籤:AC的題解分享堆疊演算法資料結構

給定一個最大容量為 M 的堆疊,將 N 個數字按 1, 2, 3, …, N 的順序入棧,允許按任何順序出棧,則哪些數字序列是不可能得到的?例如給定 M=5、N=7,則我們有可能得到{ 1, 2, 3, 4, 5, 6, 7 },但不可能得到{ 3, 2, 1, 7, 5, 6, 4 }。

輸入格式:

輸入第一行給出 3 個不超過 1000 的正整數:M(堆疊最大容量)、N(入棧元素個數)、K(待檢查的出棧序列個數)。最後 K 行,每行給出 N 個數字的出棧序列。所有同行數字以空格間隔。

輸出格式:

對每一行出棧序列,如果其的確是有可能得到的合法序列,就在一行中輸出YES

,否則輸出NO

輸入樣例:

5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2

輸出樣例:

YES
NO
NO
YES
NO

題解

注意審題,看清楚題目輸出

#include <bits/stdc++.h>
using namespace std;
ostream &sp(ostream &output);
int main()
{
    std::ios::sync_with_stdio(false);
    int maxSize;
    int n;
    int
times; cin >> maxSize >> n >> times; for (int i = 0; i < times; ++i) { stack<int> s1; deque<int> deq1; vector<int> before; vector<int> after; for (int j = 1; j <= n; ++j) { int x; cin >>
x; before.push_back(x); deq1.push_back(x); } bool flag = true; for (int j = 1; j <= n; ++j) { s1.push(j); if (s1.size() > maxSize) { flag = false; break; } while (!s1.empty() && !deq1.empty() && s1.top() == deq1.front()) { after.push_back(s1.top()); s1.pop(); deq1.pop_front(); } } if (flag) { while (!s1.empty()) { after.push_back(s1.top()); s1.pop(); } if (before == after) cout << "YES" << endl; else cout << "NO" << endl; } else cout << "NO" << endl; } return 0; }