算法导论 第八章答案

算法导论 第八章答案
算法导论 第八章答案

8.2-4 :在O(1)的时间内,回答出输入的整数中有多少个落在区间[a...b]内。给出的算法的预处理时间为O(n+k)

算法思想:利用计数排序,由于在计数排序中有一个存储数值个数的临时存储区C[0...k],利用这个数组即可。

#include

using namespace std;

//通过改编计数排序而来,因为有些部分需要注释掉

void counting_sort(int*&a, int length, int k, int*&b, int*&c);

int main()

{ const int LEN =100;

int*a =newint[LEN];

for(int i =0; i < LEN; i++)

a[i] = (i -50)*(i -50) +4;

int* b =new int[LEN];

const int k =2504;

int* c =new int[k +1];

counting_sort(a, LEN, k, b, c);

//这里需要注释掉

//for(int i = 0; i < LEN; i++)

//cout<

int m; int n;

while(cin>>m>>n)

{ if(m >n)

cout<<"区间输入不对"<

else { if(n <0) cout<<"个数为"<<0<

else if(m <=0&& n <= k) cout<<"个数为"<

else if(n > k && m >0) cout<<"个数为"<

else if(n > k && m <=0) cout<<"个数为"<

else cout<<"个数为"<

}} return 0; }

void counting_sort(int*&a, int length, int k, int*&b, int*&c)

{ for(int i =0; i < k +1; i++) c[i] =0;

for(int i =0; i < length; i++) c[a[i]]++;

for(int i =1; i < k +1; i++) c[i] = c[i] + c[i-1];

//这里需注释,因为对c数组内的元素进行减减操作会使其改变

/*for(int i = length - 1; i >= 0; i--)

{

b[c[a[i]] - 1] = a[i];

c[a[i]]--;

}*/ }

PS:计数排序的总时间为O(k+n),在实践中,如果当k = O(n)时,我们常常采用计数排序,

这时其运行时间为O(n)

8.3-4 :说明如何在O(n)时间内,对0到n^2 - 1之间的n个整数进行排序。

算法思想:1.把这n个数看成n进制数,那么每个数只有两位,因而循环只需两次

2.调用通用的基数排序(在这写着,留着以后用)

在此题中我选择n = 15,即数组中有15个数,依次为0, 3, 8, ..., 224,但是将顺序打乱

采用的是基数排序,在实践中,其排序时间为O(d*(n+k)),但很耗内存,有时甚至比快速排序更快,具体应用再看。

#include

#include

using namespace std;

void radix_sort(int a[], const int d, const int length, int radix);

int getBit(int m, int i, int radix);

int pow2(int a, int b);

int main()

{ //数组长度const int LEN =15;

int a[LEN] = {35, 48, 0, 8, 15, 80, 99, 3, 24, 168, 195, 224, 63, 120, 143}; //多少位const int d =2;

//基数const int radix =15;

//在这调用的是通用的基数排序算法,可以任意改变基数radix, //但记得改变d,因为radix改变的话,数字的位数会改变, //最简单的是十进制改成二进制,位数激增 radix_sort(a, d, LEN, radix);

for(int i =0; i < LEN; i++) cout<

{ //存储a中每个元素的余数int* remainder =new int[length];

//统计余数(等同于计数排序中的c) int* c =new int[radix];

//保存排序之后的a int* b =new int[length];

for(int i =0; i < radix; i++) c[i] =0;

for(int i =0; i < d; i++) { for(int j =0; j < length; j++)

{ int temp = getBit(a[j], i, radix); remainder[j] = temp; c[temp]++; } for(int k =1; k < radix; k++) c[k] = c[k] + c[k -1];

for(int k =length-1; k >=0; k--)

{b[--c[remainder[k]]] = a[k];//c[remainder[k]]--;}

for(int k =0; k < radix; k++) c[k] =0;

for(int i =0; i < length; i++) a[i] = b[i]; }

delete remainder; delete c; delete b; }

//得到相应位上的数值int getBit(int m, int i, int radix)

{ return (m%(pow2(radix, i +1)))/pow2(radix, i); }

//只处理指数b>=0 int pow2(int a, int b)

{ if(b >0) { int result = a;

for(int i =0; i < b -1; i++) result = result*a; return result; }

else if(b ==0) return 1;

else {cout<<"不处理指数小于零的情况"<

思考题8-2以线性时间原地排序

假设有一个有n个数据记录组成的数组要排序,且每个记录的关键字的值为0或1。排序这样一组记录的一个算法应具备如下三个特性中的一部分。

1)算法的运行时间为O(n)。

2)算法是稳定的。

3)算法是原地排序的,它可以使用除输入数组以外的固定量的存储空间。

a)给出一个满足上述条件1和条件2的算法。

b)给出一个满足上述条件1和条件3的算法。

c)给出一个满足上述条件2和条件3的算法。

d)在a)~c)中给出的算法能否用来在O(bn)时间内排序,对有b位关键字的n个记录进行基数排序?如果行,说明如何做;如果不行,说明原因。

e)假设一个n个记录中每个的关键字都介于1到k之间。说明如何修改计数排序,使得可以在O(n+k)时间内对n个记录原地排序。除输入数组外,可另用O(k)的存储空间。你给出算法是稳定的吗?(提示:当k=3时应该如何做)

问题解答:

a)使用计数排序即可满足要求。

b)由于记录的关键字的值只有两种情况(0或1),可使用类似快速排序中PARTITION将数组划分为两个区域,一区域只含关键字值均为0,另一区域关键字均为1。

具体算法为:

PARTITON-SORT(A)

n ← lenght[A]

i ← 1

while A[i] = 0 and i ≤ n

do i ← i + 1

p← i

i ← i - 1

for j ← p to n

do if A[j] = 0

then i ← i + 1

exchange A[i] ? A[j]

c)使用插入排序或合并排序即可满足要求

d)

1、a)算法可以,对数组元素的每一位的排序都采用计数排序即可。

2、b)算法不可以,是由于快速排序算法的数组分割是不稳定的。

3、c)算法也不可以,是由于插入排序和合并排序的最坏运行时间为O(n^2)。

算法导论 第三版 第24章 答案 英

Chapter24 Michelle Bodnar,Andrew Lohr April12,2016 Exercise24.1-1 If we change our source to z and use the same ordering of edges to decide what to relax,the d values after successive iterations of relaxation are: s t x y z ∞∞∞∞0 2∞7∞0 25790 25690 24690 Theπvalues are: s t x y z NIL NIL NIL NIL NIL z NIL z NIL NIL z x z s NIL z x y s NIL z x y s NIL Now,if we change the weight of edge(z,x)to4and rerun with s as the source,we have that the d values after successive iterations of relaxation are: s t x y z 0∞∞∞∞ 06∞7∞ 06472 02472 0247?2 Theπvalues are: s t x y z NIL NIL NIL NIL NIL NIL s NIL s NIL NIL s y s t NIL x y s t NIL x y s t 1

Note that these values are exactly the same as in the worked example.The di?erence that changing this edge will cause is that there is now a negative weight cycle,which will be detected when it considers the edge(z,x)in the for loop on line5.Since x.d=4>?2+4=z.d+w(z,x),it will return false on line7. Exercise24.1-2 Suppose there is a path from s to v.Then there must be a shortest such path of lengthδ(s,v).It must have?nite length since it contains at most|V|?1 edges and each edge has?nite length.By Lemma24.2,v.d=δ(s,v)<∞upon termination.On the other hand,suppose v.d<∞when BELLMAN-FORD ter-minates.Recall that v.d is monotonically decreasing throughout the algorithm, and RELAX will update v.d only if u.d+w(u,v)

算法导论第二章答案

第二章算法入门 由于时间问题有些问题没有写的很仔细,而且估计这里会存在不少不恰当之处。另,思考题2-3 关于霍纳规则,有些部分没有完成,故没把解答写上去,我对其 c 问题有疑问,请有解答方法者提供个意见。 给出的代码目前也仅仅为解决问题,没有做优化,请见谅,等有时间了我再好好修改。 插入排序算法伪代码 INSERTION-SORT(A) 1 for j ← 2 to length[A] 2 do key ←A[j] 3 Insert A[j] into the sorted sequence A[1..j-1] 4 i ←j-1 5 while i > 0 and A[i] > key 6 do A[i+1]←A[i] 7 i ←i ? 1 8 A[i+1]←key C#对揑入排序算法的实现: public static void InsertionSort(T[] Input) where T:IComparable { T key; int i; for (int j = 1; j < Input.Length; j++) { key = Input[j]; i = j - 1; for (; i >= 0 && Input[i].CompareTo(key)>0;i-- ) Input[i + 1] = Input[i]; Input[i+1]=key; } } 揑入算法的设计使用的是增量(incremental)方法:在排好子数组A[1..j-1]后,将元素A[ j]揑入,形成排好序的子数组A[1..j] 这里需要注意的是由于大部分编程语言的数组都是从0开始算起,这个不伪代码认为的数组的数是第1个有所丌同,一般要注意有几个关键值要比伪代码的小1. 如果按照大部分计算机编程语言的思路,修改为: INSERTION-SORT(A) 1 for j ← 1 to length[A] 2 do key ←A[j] 3 i ←j-1

算法导论习题答案

Chapter2 Getting Start 2.1 Insertion sort 2.1.2 将Insertion-Sort 重写为按非递减顺序排序 2.1.3 计算两个n 位的二进制数组之和 2.2 Analyzing algorithms 当前n-1个元素排好序后,第n 个元素已经是最大的元素了. 最好时间和最坏时间均为2()n Θ 2.3 Designing algorithms 2.3.3 计算递归方程的解 22()2(/2)2,1k if n T n T n n if n for k =?=?+ = >? (1) 当1k =时,2n =,显然有()lg T n n n = (2) 假设当k i =时公式成立,即()lg 2lg 22i i i T n n n i ===?, 则当1k i =+,即12i n +=时, 2.3.4 给出insertion sort 的递归版本的递归式 2.3-6 使用二分查找来替代insertion-sort 中while 循环内的线性扫描,是否可以将算法的时间提高到(lg )n n Θ? 虽然用二分查找法可以将查找正确位置的时间复杂度降下来,但

是移位操作的复杂度并没有减少,所以最坏情况下该算法的时间复杂度依然是2()n Θ 2.3-7 给出一个算法,使得其能在(lg )n n Θ的时间内找出在一个n 元素的整数数组内,是否存在两个元素之和为x 首先利用快速排序将数组排序,时间(lg )n n Θ,然后再进行查找: Search(A,n,x) QuickSort(A,n); i←1; j←n; while A[i]+A[j]≠x and i,()()b b n a n +=Θ 0a >时,()()2b b b b n a n n n +<+= 对于121,2b c c ==,12()b b b c n n a c n <+< 0a <时,()b b n a n +<

《算法导论2版》课后答案_加强版2

1 算法导论第三次习题课 2008.12.17

2 19.1-1 如果x 是根节点:degree[sibling[x]] > sibling[x] 如果x 不是根节点:degree[sibling[x]] = sibling[x] –119.1-3 略

3 19.2-2 过程略( union 操作) 19.2-3 (1)decrease-key (2)extract-min 过程略 19.2-6 算法思想:找到堆中最小值min ,用min-1代替-∞. [遍历堆中树的根节点]

4 15.1-1 15.1-2 略P195 或P329 15.1-4 f i [j]值只依赖f i [j-1]的值,从而可以从2n 压缩为2个。再加上f*、l*、l i [j]。 Print-station(l, I, j ) //i 为线路,j 为station if j>1 then Print-station(l, l i [j], j-1 ) print “line”I, “station”j;

5 15.2-1 略(见课本) 15.2-2 15.2-4 略 MATRIX-CHAIN-MULTIPLY(A, s, i, j) if j>i x= MATRIX-CHAIN-MULTIPLY(A, s, s(i,j), j) y= MATRIX-CHAIN-MULTIPLY(A, s, s(i,j)+1,j) return MATRIX-MULTIPLY(x, y) else return A i

6 15.3-1 (归纳法)递归调用 枚举15.3-2 没有效果,没有重叠子问题 15.3-4 略 (3)n Ο3/2(4/) n n Θ

算法导论 第八章答案

8.2-4 :在O(1)的时间内,回答出输入的整数中有多少个落在区间[a...b]内。给出的算法的预处理时间为O(n+k) 算法思想:利用计数排序,由于在计数排序中有一个存储数值个数的临时存储区C[0...k],利用这个数组即可。 #include using namespace std; //通过改编计数排序而来,因为有些部分需要注释掉 void counting_sort(int*&a, int length, int k, int*&b, int*&c); int main() { const int LEN =100; int*a =newint[LEN]; for(int i =0; i < LEN; i++) a[i] = (i -50)*(i -50) +4; int* b =new int[LEN]; const int k =2504; int* c =new int[k +1]; counting_sort(a, LEN, k, b, c); //这里需要注释掉 //for(int i = 0; i < LEN; i++) //cout<>m>>n) { if(m >n) cout<<"区间输入不对"< k && m >0) cout<<"个数为"< k && m <=0) cout<<"个数为"<= 0; i--) { b[c[a[i]] - 1] = a[i]; c[a[i]]--; }*/ } PS:计数排序的总时间为O(k+n),在实践中,如果当k = O(n)时,我们常常采用计数排序,

算法导论 第三版 第35章 答案 英

Chapter35 Michelle Bodnar,Andrew Lohr April12,2016 Exercise35.1-1 We could select the graph that consists of only two vertices and a single edge between them.Then,the approximation algorithm will always select both of the vertices,whereas the minimum vertex cover is only one vertex.more generally,we could pick our graph to be k edges on a graph with2k vertices so that each connected component only has a single edge.In these examples,we will have that the approximate solution is o?by a factor of two from the exact one. Exercise35.1-2 It is clear that the edges picked in line4form a matching,since we can only pick edges from E ,and the edges in E are precisely those which don’t share an endpoint with any vertex already in C,and hence with any already-picked edge. Moreover,this matching is maximal because the only edges we don’t include are the ones we removed from E .We did this because they shared an endpoint with an edge we already picked,so if we added it to the matching it would no longer be a matching. Exercise35.1-3 We will construct a bipartite graph with V=R∪L.We will try to construct it so that R is uniform,not that R is a vertex cover.However,we will make it so that the heuristic that the professor(professor who?)suggests will cause us to select all the vertices in L,and show that|L|>2|R|. Initially start o?with|R|=n?xed,and L empty.Then,for each i from 2up to n,we do the following.Let k= n i .Select S a subset of the vertices of R of size ki,and so that all the vertices in R?S have a greater or equal degree.Then,we will add k vertices to L,each of degree i,so that the union of their neighborhoods is S.Note that throughout this process,the furthest apart the degrees of the vertices in R can be is1,because each time we are picking the smallest degree vertices and increasing their degrees by1.So,once this has been done for i=n,we can pick a subset of R whose degree is one less than the rest of R(or all of R if the degrees are all equal),and for each vertex in 1

算法导论 课后题答案

Partial Solutions for Introduction to algorithms second edition Professor: Song You TA: Shao Wen

ACKNOWLEDGEMENT CLASS ONE: JINZI CLASS TWO: LIUHAO, SONGDINMIN, SUNBOSHAN, SUNYANG CLASS FOUR:DONGYANHAO, FANSHENGBO, LULU, XIAODONG, CLASS FIVE:GAOCHEN, WANGXIAOCHUAN, LIUZHENHUA, WANGJIAN, YINGYING CLASS SIX: ZHANGZHAOYU, XUXIAOPENG, PENGYUN, HOULAN CLASS: LIKANG,JIANGZHOU, ANONYMITY The collator of this Answer Set, SHAOWen, takes absolutely no responsibility for the contents. This is merely a vague suggestion to a solution to some of the exercises posed in the book Introduction to algorithms by Cormen, Leiserson and Rivest. It is very likely that there are many errors and that the solutions are wrong. If you have found an error, have a better solution or wish to contribute in some constructive way please send an Email to shao_wen_buaa@https://www.360docs.net/doc/983907535.html, It is important that you try hard to solve the exercises on your own. Use this document only as a last resort or to check if your instructor got it all wrong. Have fun with your algorithms and get a satisfactory result in this course. Best regards, SHAOWen

算法导论第三版答案

Solution to Exercise2.2-2 S ELECTION-S ORT.A/ n D A:length for j D1to n 1 smallest D j for i D j C1to n if A?i

2-2Selected Solutions for Chapter2:Getting Started A?low::high contains the value .The initial call to either version should have the parameters A; ;1;n. I TERATIVE-B INARY-S EARCH.A; ;low;high/ while low high mid D b.low C high/=2c if ==A?mid return mid elseif >A?mid low D mid C1 else high D mid 1 return NIL R ECURSIVE-B INARY-S EARCH.A; ;low;high/ if low>high return NIL mid D b.low C high/=2c if ==A?mid return mid elseif >A?mid return R ECURSIVE-B INARY-S EARCH.A; ;mid C1;high/ else return R ECURSIVE-B INARY-S EARCH.A; ;low;mid 1/ Both procedures terminate the search unsuccessfully when the range is empty(i.e., low>high)and terminate it successfully if the value has been found.Based on the comparison of to the middle element in the searched range,the search continues with the range halved.The recurrence for these procedures is therefore T.n/D T.n=2/C?.1/,whose solution is T.n/D?.lg n/.

算法导论 第三版 第一章 答案 英

Chapter1 Michelle Bodnar,Andrew Lohr April12,2016 Exercise1.1-1 An example of a real world situation that would require sorting would be if you wanted to keep track of a bunch of people’s?le folders and be able to look up a given name quickly.A convex hull might be needed if you needed to secure a wildlife sanctuary with fencing and had to contain a bunch of speci?c nesting locations. Exercise1.1-2 One might measure memory usage of an algorithm,or number of people required to carry out a single task. Exercise1.1-3 An array.It has the limitation of requiring a lot of copying when re-sizing, inserting,and removing elements. Exercise1.1-4 They are similar since both problems can be modeled by a graph with weighted edges and involve minimizing distance,or weight,of a walk on the graph.They are di?erent because the shortest path problem considers only two vertices,whereas the traveling salesman problem considers minimizing the weight of a path that must include many vertices and end where it began. Exercise1.1-5 If you were for example keeping track of terror watch suspects,it would be unacceptable to have it occasionally bringing up a wrong decision as to whether a person is on the list or not.It would be?ne to only have an approximate solution to the shortest route on which to drive,an extra little bit of driving is not that bad. 1

相关文档
最新文档