知识点
- 栈的可生成性
题目
1.3.45 栈的可生成性。假设我们的栈测试用例会进行一系列的入栈和出栈操作,序列中的整数 0, 1, ... , N - 1 (按此先后顺序排列)表示入栈操作,N个减号表示出栈操作。设计一个算法,判定给定的混合序列是否会使数组向下溢出(你使用的空间量与 N 无关,即不能用某种数据结构存储所有整数)。设计一个线性时间算法判定我们的测试用例能否产生某个给定的排列(这取决于出栈操作指令的出现位置)。解答:除非等于某个整数 k,前 k 次出栈操作会在前 k 次入栈操作前完成,否则栈不会向下溢出。如果某个排列可以产生,那么它产生的方式一定是唯一的:如果输出排列中的整数在栈顶,则将它弹出,否则将它压入栈之中。
1.3.45 Stack generability. Suppose that we have a sequence of intermixed push and pop operations as with our test stack client, where the integers 0, 1, ..., N-1 in that order (push directives) are intermixed with N minus signs (pop directives). Devise an algorithm that determines whether the intermixed sequence causes the stack to underflow. (You may use only an amount of space independent of N—you cannot store the integers in a data structure.) Devise a linear-time algorithm that determines whether a given permutation can be generated as output by our test client (depending on where the pop directives occur).
Solution: The stack does not overflow unless there exists an integer k such that the first k pop operations occur before the first k push operations. If a given permutation can be generated, it is uniquely generated as follows: if the next integer in the output permutation is in the top of the stack, pop it; otherwise, push it onto the stack.
分析
大家可能需要多读几遍题目才能看懂。但一旦看懂了,大家应该知道,这个就是书中的算数表达式求值的题目。举例:
1 - 2 -
这个时候 k = 2,意思就是,如果“前 2 次出栈操作会在前 2 次入栈操作前完成会引起栈溢出。”
不会溢出的顺序为:
- push 1
- push 2
- pop
- pop
会溢出的操作为: - pop
....
这是没有向下溢出的。因为 push 了两次(分别 push 了 “1” 和 “2”),但只 pop 了一次( “-” 即是pop 了一次 )。
答案
解答:除非等于某个整数 k,前 k 次出栈操作会在前 k 次入栈操作前完成,否则栈不会向下溢出。如果某个排列可以产生,那么它产生的方式一定是唯一的:如果输出排列中的整数在栈顶,则将它弹出,否则将它压入栈之中。
题目
1.3.46 栈的可生成性问题中禁止出现的排列。若三元组 (a, b, c) 中 a < b < c 且 c 最先被弹出,a 第二,b 第三(c 和 a 以及 a 和 b 之间可以间隔其他整数),那么当且仅当排列中不含这样的三元组时(如上题所述的)栈才可能生成它。
1.3.46 Forbidden triple for stack generability. Prove that a permutation can be generated by a stack (as in the previous question) if and only if it has no forbidden triple (a, b, c) such that a < b < c with c first, a second, and b third (possibly with other intervening integers between c and a and between a and b).
Partial solution: Suppose that there is a forbidden triple (a, b, c). Item c is popped before a and b, but a and b are pushed before c. Thus, when c is pushed, both a and b are on the stack. Therefore, a cannot be popped before b.
答案
部分解答:设有一个这样的三元组(a,b,c)。c 会在 a 和 b 之前弹出,但 a 和 b 会在 c 之前被压入。因此,当 c 被压入时,a 和 b 都已经在栈之中了。所以 a 不可能在 b 之前被弹出。
分析
本人所有简书的算法文章详细分析已经移入小专栏:算法四习题详解,欢迎大家订阅
证明
本人所有简书的算法文章详细分析已经移入小专栏:算法四习题详解,欢迎大家订阅