The priority of a page is relative to other pages: given two pages a and b, which page should be retained over the other? For example, in LRU it is that page that was more recently referenced, for Optimal it is the one that will be referenced first in the future, and for LFU it is the one that has been referenced more often in the past. Note that all of these priorities are independent of the number of page frames. FIFO also has such a priority--a < b if b came into physical memory before a did--but the priority is not independent of the number of page frames and hence FIFO is not a stack page replacement policy.
The state of physical memory is represented by a column, where the first m rows represent the contents of physical memory containing m page frames. Clearly, when a page is referenced it must be in the first row (otherwise, it would not be paged into a physical memory containing only one page frame).
The stack is easy to maintain. There are two cases to consider: a reference
to a page that is already in the stack and a reference to a page that is
not in the stack. For the first case, consider the following stack. Assume
that page r is referenced in this state.
The next state of the stack will have r on top, and a will move somewhere in the part of the stack marked dynamic. Other pages as well in dynamic may move down, but no page will move up (except for the page r, of course).
Let r be in row R. For values of m less than R page r is paged in, and for values of m greater than or equal to R there is no page fault. No page below r will move in the stack. Suppose otherwise: Let page s in row S move. If page s moves up, then for m = S - 1 page s is paged in without being referenced. And, if page s moves down then it would indicate for m = S page s was discarded even when there was no page fault.
Specifically, page a moves down the stack as long as the page b below it is in the dynamic range and a < b. Once a b is found such that b <= a, then a replaces b in the stack. Page b then moves down the stack until a page c is found such that c <= b is satisfied. Page b replaces c, and the procedure continues until the row vacated by r is encountered. The page that is currently moving down the stack goes in this row, completing the update of the stack.
The reference string:
Optimal: The most interesting case is the first reference to page 5. Page 5 displaced page 3 from the top. Page 4 doesn't have priority over page 3, and so 3 displaced 4. Pages 1 and 2 have priority over page 4, and so page 4 becomes the last page in the stack.
Give it a try for LFU. Once you have tried it, you can compare
your result with the solution. (Try to work it
out first before looking, though! Most people find applying the stack algorithm
more subtle than it first appeared.)