1. Trang chủ
  2. » Công Nghệ Thông Tin

Thực hành cấu trúc dữ liệu và giải thuật 3

131 14 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 131
Dung lượng 3,73 MB

Nội dung

Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3 Thực hành cấu trúc dữ liệu và giải thuật 3

Tutorial 1: Complexity Reorder the following efficiencies from the smallest to the largest: a 2n b n! c n5 d 15,000 e nlog2(n) Reorder the following efficiencies from the smallest to the largest: a nlog2(n) b n + n2 + n3 c 105 d n0.5 Determine the big-O notation for the following: a 5n5/2 + 11n2/5 b 9log2(n) + 6n c 3n4 + 8nlog2(n) d 5n2 + n3/2 + 3n5/3 Calculate the run-time efficiency of the following program segment: i = loop (i next = pHead; pHead = pTemp; // the list now is {2,3,5} //print them out while (pTemp!=NULL) { cout data; pTemp = pTemp->next; } } Listing In that way, our program looks ill-organized In Listing 3, we then improve it by combining pHead, count into a class named List Then the operation of inserting a new element into the list will be implemented as the method addFirst We also implement method display to print out the list elements Note that we use constructor to initialize the head of the list as NULL, and destructor to free the memory allocated class List { private: int count; Node* pHead; public: List() {pHead=NULL;} void addFirst(int newdata) { Node* pTemp = new Node; pTemp->data = newdata; pTemp->next = pHead; pHead = pTemp; count++; } void display() { Node* pTemp = pHead; while (pTemp!=NULL) { cout data; pTemp = pTemp->next; } } ~List() { Node* pTemp = pHead; while (pTemp!=NULL) { pTemp = pTemp->next; delete pHead; pHead = pTemp; } } } Listing Having the List class implemented, the main function can be rewritten far simpler as depicted in Listing void main() { List aList; aList.addFirst(5); aList.addFirst(3); aList.addFirst(2); aList.display(); } Listing The implementation of a class for linked list as above-described in this section is just an example There are many other variations of implementations for linked list as discussed in the Appendix section Students can choose what they feel appropriate when working with exercises and assignments EXERCISES 4.1 Rewrite the main function in Listing to build and display a linked list as follows {12, 5, 79, 82, 21, 43, 31, 35, 57} 4.2 Consider the following function List* buildLinkedList() { List *pList = new List; int valid=1; char choice; int num; while (valid) { cout > choice; if ((choice == ‘Y’) || (choice == ‘y’)) { cin >> num; pList->addFirst(num); } else valid = 0; } return pList; } Rewrite the main function in Exercise 4.1 to the following tasks: - use the buildLinkedList function to create a list based on input from user display the list free the memory allocated to the list 4.3 Write for the class List in Listing an additional method int addFirstIfPrime(int n) which adds n to the list if n is a prime integer In that case the returned result is 1, otherwise 4.4 Write for the class List in Listing an additional method int addLast(int n) which adds n to the last position of the list 4.5 Implement the following method int findMax(List* pList) It will return the maximum element data of the given list Assume that pList is always non-empty For example, when called with the list as built in Exercise 4.1, the returned result is 82 APPENDIX This section introduces various techniques on how to implement linked list in C/C++ For more information, please refer to the lecture note in file “Chapter2_LinkedList_Implementation.pdf” on Sakai a Pointer in C++ Node *ptr; ptr = new Node(); Khai báo trỏ ptr có kiểu Node *, nghĩa trỏ để chứa địa vùng nhớ kiểu Node Cấp phát vùng nhớ cho trỏ ptr đến printf(“Data in node: %d”, ptr->data); In giá trị kiểu int thành phần data vùng nhớ (kiểu Node) trỏ ptr đến (Có thể gọi tắt thành phần data trỏ ptr.) delete ptr; Hủy vùng nhớ trỏ ptr (con trỏ ptr đến) ptr = NULL; Gán trỏ ptr đến NULL b Nodes in C++ node data link end node //C struct struct Node { int data; Node * link; }; //C++ template struct template struct Node { ItemType data; Node * link; }; //C++ template class template class Node { ItemType data; Node * link; public: Node() { //default constructor: is called in creating, for example by calling new Node() this->link = NULL;} Node(ItemType data) { //constructor: is called in creating with parameters, for example by calling new Node(data) this->data = data; this->link = NULL; } }; Node *p = new Node(); //default constructor Node *q = new Node(3.2); //constructor Node z(0.5); //constructor c Linked List in C++ list count head end list //C struct struct List { int count; Node * head; }; //C++ template struct template struct List { int count; Node * head; }; //C++ template class template class List { int count; Node * head; public: List(); //constructor: use to initialize internal data list head tail end list No structure list ~List(); //destructor: use to release internal data }; //C++ template class template class List { Node * head; Node * tail; public: List(); //constructor: use to initialize internal data ~List(); //destructor: use to release internal data }; //Only a pointer for the head of the list Node * list; Node * list; d Linked List Operations in C++ algorithm createList (ref list //C struct ) void createList(List &list) { Initializes metadata for a linked list list.head = NULL; Pre list is a metadata structure passed by list.count = 0; reference } Post metadata initialized //C++ template class, default constructor template list.head = null LinkedList::LinkedList(){ list.count = this->head = NULL; return this->count = 0; end createList } algorithm destroyList (ref list //C struct ) void destroyList(List &list) { Node *tmp; Deletes all data in list while (list.head != NULL){ Pre list is metadata structure to a valid temp = list.head; list list.head = list.head->next; Post all data deleted delete temp; loop (list.head not null) } tmp = list.head list.count = 0; list.head = list.head-> link } A-> B -> E -> G -> F -> H -> J -> L -> O J I H F G G F E E E E E G C C C F F F F E B B B B C C C C C A B A A A A A L K H I F G E E C F B C A O N M J K H I F G E E C F B C A Top of Stack Figure BreadthFirst Search: A -> B -> E -> F -> H -> J -> L-> O Rear A B E C A G D B E G F B G D B F E C C G C F G B F G B H G E F E C J C I G F H J L K H H J L O N M L J O J N L L O Front d algorithm simulate (val G , val source , val dest ) search for a path from source to dest using depth-first traversal and then print out the solution Pre Post loop (more vertex v in G) predecessor (v) = null unmark(v) StackObj StackObj.Push(source) loop (NOT StackObj.isEmpty()) w = StackObj.Pop() // include Top and Pop if (w is dest) StackResult // temporary stack to print the solution loop (NOT predecessor(w) is null) StackResult.Push (w) w = predecessor(w) Print source loop (NOT StackResult.isEmpty()) 1 temp = StackResult.Pop() Print temp return else if (vertex w is unmarked) mark(w) print w // print the current move loop (more vertex x adjacent to w AND x is unmarked) StackObj.Push(w) StackObj.Push(x) Predecessor(x) = w else print “back to” + w end simulate Question Figure b Represent the map in an adjacency list A -> (B,12) -> (E,18) B -> (A,12) -> (C,3) -> (D,3) C-> (B,3) -> (D,4) -> (J,19) D -> (B,3) -> (C,4) -> (E,7) -> (I,21) E -> (A,18) -> (D,7) -> (F,18) -> (G,31) F -> (E,18) -> (G,12) -> (H,3) G -> (E,31) -> (F,12) -> (Q,35) H -> (F,3) -> (I,13) -> (M,9) I -> (D,21) -> (H,13) -> (J,4) -> (L,6) J -> (C,19) -> (I,4) -> (K,7) K -> (J,7) -> (L,5) -> (O,14) L -> (I,6) -> (K,5) -> (N,6) M -> (H,9) -> (N,9) -> (Q,24) N -> (M,9) -> (P,6)->(L,6) O -> (K,14) -> (P,6) -> (Q,7) P -> (N,6) -> (O,6) -> (Q,8) Q -> (G,35) -> (M,24) -> (O,7) -> (P,8) B C D 3 C D 7 A B E A F H I F G H I K L M N O P Q 1 3 1 35 1 4 7 5 K L M N O P Q J G J E 9 9 24 6 8 c Represent the map in an adjacency matrix d algorithm ShortestPath(val source , val dest , val G ) listOfShortestPath.clear() Add source to set S loop (more vertex v in digraph) // Initiate all distances from source to v distanceNode.destination= v distanceNode.distance= weight of edge(source, v) // =∞ if source is not connected to v listOfShortestPath.Insert(distanceNode) predecessor(v) = null loop(more vertex not in S) // Add one vertex v to S on each step minWeight= infinity // Choose vertex v with smallest distance loop (more vertex w not in S) Find the distance x from source to w in listOfShortestPath if(x < minWeight) v=w minWeight= x Add v to S if (v is dest) StackResult // temporary stack to print the solution loop (NOT predecessor(v) is null) StackResult.Push (v) v = predecessor(v) Print source loop (NOT StackResult.isEmpty()) temp = StackResult.Pop() Print temp return loop (more vertex w not in S) // Update distance sof all w not in S Find the distance x from source to w in listOfShortestPath alt = minWeight+ weight of edge from v to w if(x > alt) Update distance from source to w in listOfShortestPath to alt predecessor(w) = v end ShortestPath Appendix A – An implementation of topological sorting Given a directed graph G whose vertex set V = {v1,v2,…vn} The topological order list L on V can be found applying the following steps: Initially, make L empty Construct a vertor deg = {d1,d2,…,dn} where di is the indegree of vi Repeat the following tasks until all of vertices in V are put into L: - Find the largest i such that di = and vi has not been put into L - Put vi into L - For each vj such that vj is adjacent to vi and vj has not been put in L, make dj = dj-1 Figure Example 1: Consider the graph in Figure 7, we have V = {0,1,2,3,4}, the initial deg = {0,4,1,1,0} and L = () At the beginning, we have d0 = and d4 = 0, in the meantime neither nor have been put in L Thus we choose i = (the largest) and put into L Thus, L becomes (4) Since and are adjacent to 4, we decrease the value of d1 and d2 accordingly Therefore, deg becomes {0,3,0,1,0} Similarly, in the next step we choose i = and put i into L L becomes (4,2) and deg = {0,2,0,1,0} Next, we choose i = L becomes (4,2,0) and deg = {0,1,0,0,0} Next, we choose i = L becomes (4,2,0,3) and deg = {0,1,0,0,0} The last one to be put into L is 1, and the final topological list L to be found is (4,2,0,3,1) TUTORIAL SESSION BINARY TREE Question a Given a list of integers as follows, insert those integers into an empty BST one-by-one Suppose that the numbers will be added to the tree in the same order as that of the list {59, 17, 4, 13, 72, 91, 87, 21, 33, 60, 71, 1, 19} b Randomly re-order the list in Question 1a as follows Please generate the BST again (from an empty BST) (The purpose is to observe the input-order-sensitive of the BST.) {71, 1, 4, 13, 87, 91, 72, 33, 21, 60, 59, 17, 19} c Redraw the BST after deleting the node 60 from the BST in Question 1a d Redraw the BST after deleting the node 71 from the BST in Question 1b Question a Given a list of integers as follows, generate the corresponding AVL tree by inserting numbers in the list one-by-one from an empty AVL {71, 1, 4, 13, 87, 91, 72, 33, 19, 60, 59, 21, 17} b Re-do question 2a with the list as follows {1, 4, 71, 13, 87, 33, 72, 91, 19, 60, 59, 17, 21} Question Given the following algorithm of balancing the tree as presented in Listing algorithm recursive_Insert (ref subroot , val DataIn , ref taller ) Inserts a new node into an AVL tree Pre subroot points to the root of a tree/ subtree DataIn contains data to be inserted into the subtree Post If the key of DataIn already belongs to the subtree, duplicate_error is returned Otherwise, DataIn is inserted into the subtree in such a way that the properties of an AVL tree are preserved If the subtree is increased in height, the parameter taller is set to TRUE; otherwise it is set to FALSE Return duplicate_error or success Uses recursive_Insert , left_balance, right_balance functions result = success if (subroot is NULL) Allocate subroot subroot ->data = DataIn taller = TRUE else if (DataIn = subroot ->data) result = duplicate_error taller = FALSE else if (DataIn < subroot ->data) // Insert in left subtree result = recursive_Insert(subroot->left, DataIn, taller_temp ) if (taller_temp = TRUE) if (balance of subroot = left_higher) left_balance (subroot) taller = FALSE // Rebalancing always shortens the tree else if (balance of subroot = equal_height) subroot->balance = left_higher taller = TRUE else if (balance of subroot = right_higher) subroot->balance = equal_height taller = FALSE else // (DataIn > subroot ->data) Insert in right subtree result = recursive_Insert(subroot->right, DataIn, taller_temp) if (taller_temp = TRUE) if (balance of subroot = left_higher) subroot->balance = equal_height taller = FALSE else if (balance of subroot = equal_height) subroot->balance = right_higher taller = TRUE else if (balance of subroot = right_higher) right_balance (subroot) taller = FALSE // Rebalancing always shortens the tree return result end recursive_Insert Listing – recursive_Insert algorithm Fill the appropriate value to the following Table old value of subroot->balance subtree to be inserted returned taller_temp new value of subroot->balance returned value of taller equal_height equal_height equal_height equal_height … left left right right true false true false left_higher ? ? ? true ? ? ? Explaination: In the second row, the initial value of subroot->balance is equal_height The new data will be inserted into the left subtree The returned taller_temp is true, meaning that the height of the left subtree will be increased after the insertion Thus, based on the algorithm, the new value of subroot->balance should be left_higher and the returned value of taller should be true Question Write an auxiliary recursive function of a Binary Tree ADT in pseudocode to validate a BST given as a subroot pointer Also write a method in pseudocode to validate the BST algorithm checkBST_recur (val subroot , ref , ref max ) This algorithm check if the input subroot is a BST recursively Pre subroot points to a root of the subtree Post and max are the smallest and largest value in the subtree Return true if the subtree is a BST, false otherwise end checkBST_recur algorithm isBST () This algorithm check if the tree is a BST Pre Post Return true if the tree is a BST, false otherwise end isBST Question Write an auxiliary recursive function of a Binary Tree ADT in pseudocode to validate a AVL given as a subroot pointer Also write a method in pseudocode to validate the AVL algorithm checkAVL_recur (val subroot , ref , ref max , ref height ) This algorithm check if the input subroot is an AVL recursively Pre subroot points to a root of the subtree Post and max are the smallest and largest value in the subtree and height is the height of the subtree Return true if the subtree is an AVL, false otherwise end checkAVL_recur algorithm isAVL () This algorithm check if the tree is an AVL Pre Post Return true if the tree is an AVL, false otherwise end isAVL Question Write a global function in pseudocode to generate a BST from an input list by insert elements in the list into an initial empty BST Refer to question for an example algorithm generateBSTfromList (val list ) This algorithm generate a BST from the input list Pre Post the BST is built by inserting elements in the list into an initial empty tree one-by-one from the beginning of the list Return the BST end generateBSTfromList Question Write an auxiliary recursive function of a Binary Tree ADT in pseudocode to generate an AVL from an input ordered sub-list such as: - For a sub-list from position idx_1 to idx_2, the element at position mid = (idx_1+idx_2)/2 will be the root of the sub-tree - The sub-tree on the left is build recursively from the sub-list from position idx_1 to (mid-1) - The sub-tree on the right is build recursively from the sub-list from position (mid+1) to idx_2 Also write a method in pseudocode to generate the AVL from an input ordered list algorithm buildAVLfromList_recur (val list , val idx1 , val idx2 ) This algorithm build an AVL from the input ordered list by taking the middle element in the list as the root and recursively build the left and right subtree from the left part and right part of the list Pre list is an ordered list, idx1 and idx2 initialized and list.size-1 Post the AVL is built Return the root of the AVL end buildAVLfromList_recur algorithm buildAVLfromList (val list ) This algorithm build an AVL from the input ordered list by calling the function buildAVLfromList Pre Post the AVL is built end buildAVLfromList TUTORIAL SESSION BINARY TREE Question 71 59 17 1 72 21 13 19 60 33 72 91 71 87 91 13 87 33 60 21 (a) 59 17 19 (b) 59 60 17 72 21 13 19 71 33 91 87 87 72 13 33 21 (c) 59 17 19 (d) 91 Question 2a 71,1,4: 71 // \ Rotate right 71 \\ 71 71 Rotate left 13,87,91: 13 \ \ 87 91 71 72,33,19: 71 87 13 \\ 72 33 19 91 87 / 19 13 72 33 87 13 91 60: 91 71 \\ 87 19 13 \ 72 33 19 87 33 13 71 / \\ 72 60 59 19 91 / 71 19 87 59 13 33 60 72 60 91 87 59 / 72 91 13 33 / 60 - / 59 17: 19 59 91 // \ 21 1 72 / 13 71 4 \ 21: 19 87 33 / \ 60 71 / 71 \ 33 13 \ 17 21 / 60 \ 19 87 72 91 59: \ / \ 71 33 13 21 / 60 \ 87 72 91 91 Question 2b 1,4,71: \\ 4 \ 71 13,87,33: 71 \\ 13 71 13 \ 13 71 33 / \ 33 87 60 59 / 72 13 91 33 13 17,21: / \\ / 19 87 33 72,91,19,60, 59: / 71 19 17 60 21 71 19 60 59 / 87 72 91 / / / 59 / 87 72 91 Question old value of subroot->balance subtree to be inserted returned taller_temp new value of subroot->balance returned value of taller equal_height equal_height equal_height equal_height left_higher left_higher left_higher left_higher right_higher right_higher right_higher right_higher left left right right left left right right left left right right true false true false true false true false true false true false left_higher equal_height right_higher equal_height equal_height left_higher equal_height left_higher equal_height right_higher equal_height right_higher true false true false false false false false false false false false 71 33 87 Question algorithm checkBST_recur (val subroot , ref , ref max ) This algorithm check if the input subroot is a BST recursively Pre subroot points to a root of the subtree Post and max are the smallest and largest value in the subtree Return true if the subtree is a BST, false otherwise isBST = true if (subroot) = max = subroot->data if (subroot->left) Check the left subtree and retrieve the and the max of the left subtree The of the left subtree is also the of this tree isBST = checkBST_recur(subroot->left, min, lmax) isBST = isBST and lmax < subroot->data end if if (subroot->right) Check the right subtree and retrieve the and the max of the right subtree The max of the right subtree is also the max of this tree isBST = isBST and checkBST_recur(subroot->right, rmin, max) isBST = isBST and rmin > subroot->data end if end if return isBST end checkBST_recur algorithm isBST () This algorithm check if the tree is a BST Pre Post Return true if the tree is a BST, false otherwise return checkBST_recur(root, min, max) end isBST Question algorithm checkAVL_recur (val subroot , ref , ref max , ref height ) This algorithm check if the input subroot is an AVL recursively Pre subroot points to a root of the subtree Post and max are the smallest and largest value in the subtree and height is the height of the subtree Return true if the subtree is an AVL, false otherwise isAVL = true if (subroot) = max = subroot->data lh = rh = if (subroot->left) isAVL = checkAVL_recur(subroot->left, min, lmax, lh) isAVL = isAVL and lmax < subroot->data end if if (subroot->right) isAVL = isAVL and checkAVL_recur(subroot->right, rmin, max, rh) isAVL = isAVL and rmin > subroot->data end if isAVL = isAVL and ((lh == rh) or (lh == rh + 1) or (lh + == rh)) height = (lh > rh) ? lh + : rh + end if return isAVL end checkAVL_recur algorithm isAVL () This algorithm check if the tree is an AVL Pre Post Return true if the tree is an AVL, false otherwise return checkAVL_recur(root, min, max, height) end isAVL Question algorithm generateBSTfromList (val list ) This algorithm generate a BST from the input list Pre Post the BST is built by inserting elements in the list into an initial empty tree one-by-one from the beginning of the list Return the BST aBST = create a Binary tree idx = loop (idx < list.size()) list.retrieve (idx, x) aBST.insert (x) idx++ end loop return aBST end generateBSTfromList Question algorithm buildAVLfromList_recur (val list , val idx1 , val idx2 ) This algorithm build an AVL from the input ordered list by taking the middle element in the list as the root and recursively build the left and right subtree from the left part and right part of the list Pre list if an ordered list, idx1 and idx2 initialized and list.size-1 Post the AVL is built Return the root of the AVL subroot = null if (idx1 data) subroot->left = buildAVLfromList_recur(list, idx1, mid-1) subroot->right = buildAVLfromList_recur(list, mid+1, idx2) end if return subroot end buildAVLfromList_recur algorithm buildAVLfromList (val list ) This algorithm build an AVL from the input ordered list by calling the function buildAVLfromList Pre Post the AVL is built root = buildAVLfromList_recur (list, 0, list.size()-1) end buildAVLfromList ... kết (7 23_ 5 (722 _3 724_6)) Ví dụ 9: Với liệu nhập 17 234 172 23 17246 17771 18 234 Ví dụ 9: Với liệu nhập 17 235 172 23 17246 17771 18 234 Trước Aragorn xuất kiện thứ tư, nhị phân hành (7 23_ 5 (722 _3 724_6)),... kết (7 23_ 5 (722 _3 724_6)) Ví dụ 9: Với liệu nhập 17 234 172 23 17246 17771 18 234 Ví dụ 9: Với liệu nhập 17 235 172 23 17246 17771 18 234 Trước Aragorn xuất kiện thứ tư, nhị phân hành (7 23_ 5 (722 _3 724_6)),... thành kết sau (777_1 (7 23_ 5 (722 _3 724_6)) 8 23_ 4)) Nhầm số ví dụ 17 234 -> 17 235 Nhầm số ví dụ 17 234 -> 17 235 Assignment – Change Log ID Cũ Mới Giải thích 12 Ví dụ 17: Với liệu nhập 11 231 1 234 5

Ngày đăng: 27/02/2022, 16:02

TỪ KHÓA LIÊN QUAN