《算法导论》第五章-第3节_练习(参考答案)

这篇博客详细解答了《算法导论》第三版中第五章第3节的练习题,涉及随机化算法的正确性和概率分析。题目涵盖了循环不变式、随机排列生成及其概率验证、算法优化等多个主题。
摘要由CSDN通过智能技术生成

算法导论(第三版)参考答案:练习5.3-1,练习5.3-2,练习5.3-3,练习5.3-4,练习5.3-5,练习5.3-6,练习5.3-7

Exercise 5.3-1

Professor Marceau objects to the loop invariant used in the proof of Lemma 5.5. He questions whether it is true prior to the first iteration. He reasons that we could just as easily declare that an empty subarray contains no 0-permutations. Therefore, the probability that an empty subarray contains a 0-permutation should be 0, thus invalidating the loop invariant prior to the first iteration. Rewrite the procedure RANDOMIZE-IN-PLACE so that its associated loop invariant applies to a nonempty subarray prior to the first iteration, and modify the proof of Lemma 5.5 for your procedure.

Pseudocode

RANDOMIZE-IN-PLACE02(A)
  n = A.length
  swap A[1] with A[RANDOM(1,n)]
  for i = 2 to n
    swap A[i] with A[RANDOM(i,n)]

在证明中,初始化部分不再从空数组开始,而是从 A[i] 开始。根据循环不变式可知,初始化部分成立。

Exercise 5.3-2

Professor Kelp decides to write a procedure that produces at random any permutation besides the identity permutation. He proposes the following procedure:

PERMUTE-WITHOUT-IDENTITY(A)
n = A.length
for i = 1 to n - 1
    swap A[i] with A[RANDOM(i + 1, n)]

Does this code do what Professor Kelp intends?

(中英文版的题意貌似不一样,beside?/ except?,这里参考英文原版)

不能,因为每次置换都不可能出现第 i 个元素在相同的位置上,只会产生 (n1)! 种不同的情况。

Exercise 5.3-3

Suppose that instead of swapping element A[i] with a random element from the subarray A[in] , we swapped it with a random element from anywhere in the array:

PERMUTE-WITH-ALL(A)
n = A.length
for i = 1 to n
    swap A[i] with A[RANDOM(1,n)]

Does this code produce a uniform random permutation? Why or why not?

不能。有 nn 种方式放置元素,同时又有 n! 种排列。获得等同排列的概率是 1nnn! ,不是 1n!

拓展阅读 from Coding Horror

Exercise 5.3-4

Professor Armstrong suggests the following procedure for generating a uniform random permutation:

n = A.length
let B[1..n] be a new array
offset = RANDOM(1, n)
for i = 1 to n
    dest = i + offset
    if dest > n
        dest = dest - n
    B[dest] = A[i]
return B

Show that each element A[i] has a 1/n probability of winding up in any particular position in B . Then show that Professor Armstrong is mistaken by showing that the resulting permutation is not uniformly random.

很容易理解, A 中每一个元素出现在 B 中的任何位置的概率是 1n , 因为 P{ dest}=P{ offset}=1/n

这样做只是获得了一个在原数组 A 上的循环置换元素后的数组 B

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值