算法设计与程序分析习题精选含答案(第四章)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

作业四

4.1.2 Alternating glasses

a. There are 2n glasses standing next to each other in a row, the first n of them filled with a soda drink and the remaining n glasses empty. Make the glasses alternate in a filled-empty-filled-empty pattern in the minimum number of glass moves. [Gar78]

b. Solve the same problem if 2n glasses—n with a drink and n empty—are initially in a random order

答:

图1 杯子分组

a.两个为一组,在前n个杯子中判断偶数的杯子是否为空,不为空与同组的进行交换,共需

要交换n/2次,考虑n为奇数对n/2进行向下取整即可。

b.由于最终偶数位置为空杯,奇数位置为满杯,从第一项开始遍历,如果在奇数位置出现空

杯与后面偶数位置出现的第一个满杯进行交换,如果偶数位置出现满杯则与后面奇数出现的第一个空杯进行交换,每次交换使得两个位置满足条件,最坏情况是2n位置均为乱序,则需要交换n次,最好的情况为2n位置均满足条件,则交换次数为[0,n]

4.1.7 Apply insertion sort to sort the list E, X, A, M, P, L, E in alphabetical order.

4.2.1 Apply the DFS-based algorithm to solve the topological sorting problem for the following digraphs:

答:

(a) f

e g

b c

a d

从堆栈中弹出:efgbcad,反转输出为:dacbgfe

(b) 由于存在回环b图不是无向回环图。

4.2.5 Apply the source-removal algorithm to the digraphs of Problem 1 above.

答:(a)得到的解为:dacbgfe

图2 源删除算法

图2 b的源删除算法

(b)无解

4.3.7 Write pseudocode for a recursive algorithm for generating all 2n bit strings of length n.

4.4.10 (a) Write pseudocode for the divide-into-three algorithm for the fake-coin problem. Make sure that your algorithm handles properly all values of n, not only those that are multiples of 3.

(b) Set up a recurrence relation for the number of weighings in the divide-intothree algorithm for the fake-coin problem and solve it for n = 3k.

(c) For large values of n, about how many times faster is this algorithm than the one based on dividing coins into two piles? Your answer should not depend on n.

答:

(a)①如果硬币为3K,则将硬币分为三堆K枚硬币;如果硬币为3K+1,则将硬币分为两堆K+1,一堆K-1;如果硬币为3K+2则将硬币分为两堆K+1,一堆K。称重两堆个数一样的,②如果重量相同,则假币在第三堆中,对第三堆进行①操作再进行②操作,不断重复直至找出假币。③如果有一堆轻(假设假币为轻的)则假币在这堆里,对该堆进行①操作再进行②操作。

(b)第n次分每堆为3k−n,最坏的情况为n为k时。

=log23

(c)log2n

log3n

4.5.2 Apply quickselect to find the median of the list of numbers 9, 12, 5, 17, 20, 30, 8.

答:

import random

# 快速选择排序

def quicksort(l):

if len(l)<2:

return l

else:

r = random.randint(0, len(l)-1)

base = l[r]

del l[r]

left =[i for i in l[:]if i <= base]

right =[i for i in l[:]if i > base]

return quicksort(left)+[base]+quicksort(right)

lists =list(eval(input("请输入列表,使用逗号隔开: ")))

lists =quicksort(lists)

L =len(lists)

if L %2==0:

print((lists[int(L /2)]+ lists[int((L /2)+1)])/2)

else:

print(lists[int((L -1)/2)])

相关文档
最新文档