You are on page 1of 3

public static void main blah blah

{
input(n)
input(permutation of n numbers in array A) // elements of A
are A[1],,A[n]
string s1 = enqueue(Q2, dequeue(Q1))
string s2 = push(S, dequeue(Q1))
string s3 = enqueue(Q2, pop(S))
function f1 (input = nothing; output = boolean value) //
return true if A is a stack permutation, false otherwise
{
define x = (initially) empty stack
int b = 1
for (int i=1; i<=n; ++i)
{
if(A[i] > b)
{
for (int j=b; j<A[i]; ++j)
{
x.push(j)
}
b = A[i]+1
}
else if (A[i] == b)
{
b++
}
else
{
int c = x.pop()
if (A[i] != c)
{
return false
exit out of function
}
}
}
}

return true

function f2 (input = nothing; output = sequence of operations


that formed the permutation) // f2 is called only if A is a

stack permutation
{
int b = 1;

for (int i=1; i<=n; ++i)


{
if (A[i] == b)
{
print(s1)
}
else if (A[i] > b)
{
for (int j=b; j<A[i]; ++j)
{
print(s2)
}
b = A[i]+1
}
else
{
print(s3)
}
}

function f3 (input = nothing; output = where went wrong) // f3


is called only if A is NOT a stack permutation
{
define x = (initially) empty stack
int b = 1
for (int i=1; i<=n; ++i)
{
if(A[i] > b)
{
for (int j=b; j<A[i]; ++j)
{
x.push(j)
}
b = A[i]+1
}
else if (A[i] == b)
{
b++
}
else
{

int c = x.pop()
if (A[i] != c)
{
print(The number A[i] in the
permutation is the wrong place. The next element in the stack
was c. Therefore, in place of
A[i] we should have either c or
b(if b<=n))
exit out of function
}
}
}
}
if(f1())
{
f2()
}
else
{
f3()
}
}

You might also like