Rozwiązanie:
i: from 1 to n
j: from 1 to n, used to traverse the sequence seq[1...n]
stack: empty at the beginning
while i <= n || j <= n
IF stack is empty,
push i into stack, i plus 1;
ELSE IF the top of stack is equal to seq[j]
pop from stack, j plus 1;
ELSE IF the top of stack is larger than seq[j]
illegal sequence! Stop here!
ELSE
push i into stack, i plus 1;
legal sequence if the stack is empty!
Przykład 1: {1, 2, 4, 3} przeprowadzone prawidłowo
In the beginning, i = 1, j = 1, and stack is empty.
1. stack is empty:
stack = {1}, i = 2, j = 1.
2. top of stack 1 is equal to seq[j] = 1:
stack = {}, i = 2, j = 2.
3. stack is empty:
stack = {2}, i = 3, j = 2.
4. top of stack 2 is equal to seq[j] = 2:
stack = {}, i = 3, j = 3.
5. stack is empty:
stack = {3}, i = 4, j = 3.
6. top of stack 3 is smaller than seq[j] = 4:
stack = {3, 4}, i = 5, j = 3.
7. top of stack 4 is equal to seq[j] = 4:
stack = {3}, i = 5, j = 4.
8. top of stack 3 is equal to seq[j] = 3:
stack = {}, i = 5, j = 5.
Przykład 2: {1, 4, 2, 3}, niedozwolona sekwencja
In the beginning, i = 1, j = 1, and stack is empty.
1. stack is empty:
stack = {1}, i = 2, j = 1.
2. top of stack 1 is equal to seq[j] = 1:
stack = {}, i = 2, j = 2.
3. stack is empty:
stack = {2}, i = 3, j = 2.
4. top of stack 2 is smaller than seq[j] = 4:
stack = {2, 3}, i = 4, j = 2.
5. top of stack 3 is smaller than seq[j] = 4:
stack = {2, 3, 4}, i = 5, j = 2.
6. top of stack 4 is equal to seq[j] = 4:
stack = {2, 3}, i = 5, j = 3.
7. top of stack 3 is larger than seq[j] = 2:
illegal sequence, stop here.
Staram się jak najlepiej wyjaśnić mój pomysł, mam nadzieję, że wyjaśniłem.
@ user2246674, to nie jest to konieczne, pop oznacza się i zdejmowania pokrywy element stosu, nie możemy podać numeru, który ma zostać wyświetlony. – hiway
Ah, tak, że istnieje * dowolne * takie zamówienie .. – user2246674
Jakie było Twoje pytanie? –