Topic 1366: Stack push-in, pop-up sequence time limit: 1 seconds Memory limit: 32 Mega Special: No submission: 2143 Resolution: 816 Title Description: Enter two integer sequence, the first sequence represents the stack's indentation order, and determine if the second sequence is the pop-up order of the stack. Assume that all the numbers that are pressed into the stack are not equal. For example, the sequence 1,2,3,4,5 is the indentation order of a stack, and the sequence 4,5,3,2,1 is a pop-up sequence corresponding to the stack sequence, but 4,3,5,1,2 is not likely to be the pop-up sequence of the stack sequence. Input: Each test case consists of 3 lines: The first behavior is 1 integer n (1<=n<=100000), which indicates the length of the sequence. The second row contains n integers that represent the stacking order of the stack. The third row contains n integers that represent the pop-up order of the stack. Output: corresponding to each test case, if the second sequence is the first sequence of the pop-up sequence output yes, otherwise output No. Sample input: 51 2 3 4 54 5 3 2 151 2 3 4 54 3 5 1 2 sample output: YesNo
Be careful not to use the stack, which uses more memory than the topic limits, because it is dynamically growing, and memory is replicating, requiring a lot of memory space. The array is changed to the analog stack.
#include <iostream> #include <stdio.h> #include <stack>using namespace Std;bool ispopsequence (int* ppush,int* Ppop,int nlength) {if (ppush==null| | ppush==null| | Nlength<=0) {return false; } int* ppushnext = Ppush; int* ppopnext = Ppop; int pnext = 0; int ptop =-1; int* stackdata = new Int[nlength+1]; while (Ppopnext-ppop<nlength) {while (ptop==-1| | Stackdata[ptop]!=*ppopnext) {stackdata[pnext++] = *ppushnext; ppushnext++; ptop++; } if (Ptop>=0&&stackdata[ptop]!=*ppopnext) {return false; } pnext--; ptop--; ppopnext++; } if (Ptop==-1&&ppopnext-ppop==nlength) {return true; } return false;} int main () {int n; while (scanf ("%d", &n)!=eof) {int* a = new int[n]; int* B = new Int[n]; for (int i=0;i<n;i++) {scanf ("%d", &a[i]); } for (int i=0;i<n;i++) {sCANF ("%d", &b[i]); } if (Ispopsequence (a,b,n)) {printf ("yes\n"); }else{printf ("no\n"); }} return 0;}
The sword refers to the offer series source code-the stack's press-in, the popup sequence