7-1 Pop Sequence(25 分)
Given a stack which can keep M numbers at most. Push N numbers inthe order of1, 2, 3, ..., N and pop randomly. You are supposed to tell ifa given sequence of numbers is a possible pop sequence ofthe stack. For example, if M is 5and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7fromthe stack, but not3, 2, 1, 7, 5, 6, 4.
Input Specification:
Each input filecontainsone test case. For eachcase, thefirstlinecontains3 numbers (all no more than 1000): M (the maximum capacity ofthe stack), N (thelengthof push sequence), and K (thenumberof pop sequences to be checked). Then K lines follow, eachcontainsa pop sequence of N numbers. All the numbers inaline are separated byaspace.
Output Specification:
For each pop sequence, print inoneline"YES"ifit is indeed a possible pop sequence ofthe stack, or"NO"ifnot.
Sample Input:
57512345673217564765432156437211765432
Sample Output:
YES
NO
NO
YES
NO
#include<iostream>#include<cstdio>#include<cstring>#include<stack>usingnamespacestd;
int main()
{
int n, m, i, j, k;
while (cin >> m >> n >> k)
{
while (k--)
{
int num[1111];
for (i =0 ; i < n; i++)
scanf("%d", num + i);
stack<int> q;
int cnt = 0;
for (i = 1; i <= n; i++)
{
q.push(i);
if (q.size() > m) break;
while(!q.empty() && q.top() == num[cnt])
{
q.pop();
cnt++;
}
}
if (cnt == n)
puts("YES");
elseputs("NO");
}
}
return0;
}