DSA Final Review
DSA Final Review
Mục lục
1 Hash 2
2 Searching 7
3 Heap 11
4 Graph 15
1 Hash
Question 1 (F-231). Among the implementations of the hash probing function hash
hp(k, p, M), where k is the key and M is the memory size, which implementation is the
best for resolving collisions using the open addressing method?
A. h(k,p,M) = (a*k + b*p) % M, where a and b are two prime numbers.
B. h(k,p,M) = h1(k,M) + p*h2(k,M), where h1 and h2 are two hash functions.
C. h(k,p,M) = h1(k,M) + p*h2(k,M) mod M, where h1 and h2 are two hash
functions.
D. h(k,p,M) = rot(k,p) % M, where rot is a rotation function applied to the key p
times..
Question 2 (F-231). Given the hash function as follows: h(k, M) = rot(k, 2) % M,
where rot(k, m) is the left rotation by m digits, and M is the memory size. Please
provide the result of the following code segment:
vector<int> v {1026, 1023, 1022, 1025, 1001};
for (auto val : v) cout « h1(val, 107) « ’ ’;
A. 26 23 22 25 11. B. 42 63 70 49 3.
C. 61 31 21 51 10. D. 610 310 210 510 011.
Question 3. The key to be hashed is a character string. The hash function is defined
as follows: the sum of the current character multiplied by the remainder (when divided
by 7) of the character immediately following it, with everything taken modulo M, where
M is the memory size. Given the function int h2(string str, int M), the internal
implementation is:
A. int acc = 0; for(char c:str) acc+= c; return acc % M;.
B. for(char c: str) c += c; return c % M;.
C. Both of them are true.
D. Both of them are false.
Question 4 (F-221). Insert the keys 5, 7, 12, 25, 36, and 58 into a hash table of size 11,
using the hash function h(k) = k mod 11. If a collision occurs, the collision resolution
method chosen is open addressing with the probing function p(k, i) = h(k) + 2 ∗ i + 1.
Determine the position of key 58 in the hash table?
A. 0. B. 3. C. 6. D. 9.
Question 5 (F-221). For each of the following key sequences, insert them sequentially
into an (empty) hash table of size 19, with the hash function h(k) = k%19. Which key
sequence results in the fewest collisions?
A. 0,19,57. B. 19, 20, 21, 22, 23, 46, 47, 57.
C. 19, 20, 21, 22, 23, 40, 41, 57. D. 19, 20, 21, 39, 40.
Question 6 (F-221). Which of the following statements is correct regarding collisions
in hashing?
A. A collision occurs when two different keys produce two different hash values.
B. A collision occurs when two identical keys produce two different hash values.
C. A collision occurs when two identical keys produce the same hash value.
D. A collision occurs when two different keys produce the same hash value.
Question 7 (F-221). Which of the following statements is correct about Quadratic
probing?
A. It is a method of implementing a hash function.
B. It can lead to Primary clustering.
1. A hash function takes a message of arbitrary length and generates a fixed length
code.
2. A hash function takes a message of fixed length and generates a code of variable
length.
3. A hash function may give the same hash value for distinct messages.
if (arr[i] == arr[j]) {
int temp = abs(j - i);
value = value > temp ? value : temp;
}
return value;
}
What is the expected output if we call fun(arr,12) in the main function with arr[] =
{3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}?
A. 2. B. 10. C. 5. D. Compile error.
Question 28. What is the value of the Boundary Folding hash function with key k =
456789378 and the memory size is 1000?
A. 505. B. 623. C. 367. D. 489.
Question 29. What is the value of the Shift Folding hash function with key k = 456789378
and the memory size is 1000?
A. 505. B. 623. C. 367. D. 489.
2 Searching
Question 30 (F-231). Use the binary search algorithm to find the position of 48 in the
following sequence: [1,5,8,11,19,22,31,35,40,45,48,49,50]. How many comparisons
are required?
A. 2. B. 3. C. 4. D. 5.
Question 31 (F-231). Use the interpolation search algorithm to find the position of
48 in the following sequence: [1,5,8,11,19,22,31,35,40,45,48,49,50]. How many
comparisons are required?
A. 2. B. 3. C. 4. D. 5.
Question 32 (F-231). Given that foo3 is an interpolation search algorithm:
int foo3(int *arr, int n, int x) {
int i1 = 0, i2 = (n - 1), pos;
while (i1 <= i2 && x >= arr[i1] && x <= arr[i2]) {
if (i1 == i2) {
if (arr[i1] == x) return i1;
return -1;
}
// Line 1
if (arr[pos] == x) return pos;
if (arr[pos] < x) i1 = pos + 1;
else i2 = pos - 1;
}
return -1;
}
What is the output of the following code after execution? int arr[] = {2,3,4,10,40};
cout « foo1(arr, 0, 5, 10);
A. 0. B. 3.
C. 4. D. None of the above.
Question 34 (F-231). Given that the function foo2 implements a search algorithm:
int foo2(int arr[], int x, int n) {
int step = sqrt(n);
int prev = 0;
// Code here
while (arr[prev] < x) {
prev++;
if (prev == min(step, n)) return -1;
}
if (arr[prev] == x) return prev;
return -1;
}
Given n = 13 and target > a[n-1], determine the number of comparisons performed
in the if statements.
A. 4. B. 6. C. 7. D. 8.
Question 36 (F-221). Given the sequence: [1,5,7,8,16,30,33,35,41,49,51,52,59,61,65,68,69,71,72,
75,76,83,85,89,97] Use interpolation search to find the number 49 in the above sequence.
How many search positions were traversed before stopping?
A. 1. B. 0. C. 2. D. 3.
Question 37. What is the time complexity for performing Jump search? √
A. O(logN). B. O(N). C. O(N 2 ). D. O( N ).
Question 38. In the worst case, (for instance where the numerical values of the keys
increase exponentially) the interpolation search technique will take how many compar-
isons.?
A. O(N). B. O(logN). C. O(loglogN). D. None.
Question 39. Consider the following program that attempts to locate an element x in
a sorted array a[ ] using binary search. Assume N>1. The program is erroneous. Under
what conditions does the program fail?
if (a[k] = x) then
writeln ('x is in the array')
else
writeln ('x is not in the array')
end;
3 Heap
Question 52 (F-231). Given an array of 7 variables [x0 , ..., x6 ]. Suppose that after con-
verting this array into a min-heap, we obtain the array: [x6 , x4 , x2 , x3 , x1 , x5 , x0 ]. Which
of the following arrays could be the result of sorting the original array in ascending or-
der?
A. [x6 , x1 , x2 , x3 , x4 , x5 , x0 ]. B. [x6 , x2 , x5 , x0 , x3 , x4 , x1 ].
C. [x6 , x4 , x3 , x2 , x5 , x0 , x1 ]. D. [x6 , x4 , x1 , x3 , x5 , x2 , x0 ].
Question 53 (F-231). Given a max-heap: 90, 73, 41, 25, 36, 17, 1, 2, 3, 19, 26, 7. What
will the state of the heap be after removing 36 from the heap?
A. 90, 73, 41, 25, 26, 17, 1, 2, 3, 7, 19. B. 90, 73, 41, 25, 19, 17, 1, 2, 3, 7, 26.
C. 90, 73, 41, 25, 26, 17, 1, 2, 3, 19, 7. D. 90, 73, 41, 25, 19, 17, 1, 2, 3, 26, 7.
Question 54 (F-231). Given an array: 1, 3, 5, 4, 6, 11, 10, 8, 7, 13, 15. Which of the
following arrays represents the result after two steps of heapifying this array into a max-
heap using an O(N ) algorithm?
A. [15,13,11,8,6,5,10,4,7,3,1]. B. [1,15,11,8,13,5,10,4,7,3,6].
C. [1,3,5,8,15,11,10,4,7,13,6]. D. None of those above.
Question 55 (F-231). Which of the following arrays represents a max-heap?
A. [17,15,13,9,6,10,5,4,8,3,1]. B. [17,15,13,9,6,5,10,4,8,3,1].
C. [17,15,13,9,6,5,4,10,3,8,1]. D. [17,13,15,6,9,4,10,5,3,1,8].
Question 56 (F-231). Given an array: [10,7,11,5,4,13,1,2]. Which of the following arrays
represents the min-heap created by inserting each element of the array one by one?
A. [1, 2, 4, 5, 7, 13, 11, 10]. B. [1, 2, 5, 4, 7, 13, 11, 10].
C. [1, 2, 5, 4, 7, 11, 13, 10]. D. [1, 2, 4, 5, 7, 10, 11, 13].
Question 57 (F-231). Given a min-heap: [1,2,6,4,7,13,11,10]. Which of the following
represents the resulting min-heap if an element with the value 3 is added to the array?
A. [1, 2, 3, 4, 7, 13, 11, 10, 6]. B. [1, 2, 6, 3, 7, 13, 11, 10, 4].
C. [1, 2, 6, 4, 7, 13, 11, 10, 3]. D. [1, 2, 6, 4, 3, 13, 11, 10, 7].
Question 58 (F-231). Which of the following statements is true for a heap with height
h:
A. The element with the largest key will be the root of the heap.
B. The leaf elements of the heap are only at height h.
C. A heap is a complete binary tree.
D. All of the above statements are true.
Question 59 (F-231). The time complexity of heap construction algorithms such as
heapify and bottom-up build are respectively:
A. O(log2 n) and O(n). B. O(n) and O(log2 n).
C. O(n) and O(n). D. O(log2 n) and O(log2 n).
The following data applies to the next two questions:
class Heap{
int *harr; // pointer to array of elements in heap
int heap_size; // Current number of elements.
public:
A. C. B. D. C. A. D. B.
Question 66 (F-221). Given a max-heap containing integer values as follows: [29, 20,
10, 15, 18, 9, 5, 13, 2, 4, 15]. Sequentially extract m elements from the top of the max-
heap such that the total of these m elements does not exceed 70. Determine the value of
m.
A. 3. B. 4. C. 5. D. 2.
Sequentially insert the following integer values into an empty max-heap: 5, 10, 8, 3, 2,
14, 12, 13. Use this data to answer the next three questions.
Question 67 (F-191). If the max-heap above is represented as a binary tree, what is
the height of the tree and the smallest value of an internal node (a node that is neither a
leaf nor the root)?
A. 3, 10. B. 2, 5. C. 3, 5. D. 2, 10.
Question 68 (F-191). If one more element must be added to the above heap, which
element would cause the most swap operations during the heap adjustment process?
A. 17. B. 1. C. 11. D. 6.
Question 69 (F-191). After extracting the largest element from the heap, the array
representation of the heap is:
A. 13, 5, 12, 3, 2, 8, 10. B. 13, 12, 5, 3, 2, 8, 10.
C. 13, 5, 12, 2, 3, 10, 8. D. 13, 12, 5, 2, 3, 10, 8.
Question 70 (F-181). Which of the following statements about heaps is INCORRECT?
into the heap in that order. The level-order traversal of the heap after the insertion of the
elements is:
A. 10, 8, 7, 3, 2, 1, 5. B. 10, 8, 7, 2, 3, 1, 5.
C. 10, 8, 7, 1, 2, 3, 5. D. 10, 8, 7, 5, 3, 2, 1.
Question 75. Consider a max heap, represented by the array: 40, 30, 20, 10, 15, 16, 17,
8, 4. Now consider that a value 35 is inserted into this heap. After insertion, the new heap
is
A. 40, 30, 20, 10, 15, 16, 17, 8, 4, 35. B. 40, 35, 20, 10, 30, 16, 17, 8, 4, 15.
C. 40, 30, 20, 10, 35, 16, 17, 8, 4, 15. D. 40, 35, 20, 10, 15, 16, 17, 8, 4, 30.
Question 76. A complete binary min-heap is made by including each integer in [1, 1023]
exactly once. The depth of a node in the heap is the length of the path from the root of
the heap to that node. Thus, the root is at depth 0. The maximum depth at which integer
9 can appear is
A. 6. B. 7. C. 8. D. 9.
Question 77. Consider the array representation of a binary min-heap containing 1023
elements. The minimum number of comparisons required to find the maximum in the
heap is
A. 510. B. 511. C. 512. D. 255.
4 Graph
Question 78 (F-231). Let G be a simple graph with 20 vertices and 8 connected com-
ponents. If one vertex is removed from G, the number of connected components of G will
lie within the interval:
A. 8 and 20. B. 8 and 19. C. 7 and 19. D. 7 and 20.
Question 79 (F-231). Given a directed graph G(Vx, Ed), where Vx = {A, B, C, D,
E, F} and Ed is presented by the adjacency matrix: {0, 1, 1, 0, 0, 0}, {0, 0, 0,
0, 1, 0}, {0, 0, 0, 1, 1, 0}, {0, 0, 0, 0, 1, 1}, {1, 1, 0, 0, 0, 0}, {0, 0,
0, 0, 0, 0}. Which vertices are visited in a Breadth-First Search (BFS) to find a path
from A to F?
A. A E F. B. A B D F. C. A B C D F. D. A B C D E F.
Question 80 (F-231). To implement a Depth-First Search algorithm on a graph, which
data structure is used?
A. Queue. B. Stack. C. Heap. D. Linked List.
Question 81. Given a directed graph G(Vx, Ed), where Vx = {A, B, C, D, E, F} and
Ed is presented by the adjacency matrix: {0, 1, 1, 0, 1, 0}, {1, 0, 0, 1, 1, 0},
{1, 0, 0, 1, 1, 0}, {0, 1, 1, 0, 1, 0}, {1, 1, 1, 1, 0, 0}, {0, 0, 0, 0, 0,
0}. What is the output of the Depth-First Search (DFS) traversal for this graph?
A. A B C D E F. B. A B D C E F. C. A C D B E F. D. A E D C E F.
Use for next 5 questions:
Given the Graph class implemented using an adjacency matrix as follows:
1 class Graph {
2 private :
3 int nover ; // number of vertices
4 int ** wm ; // adjacency matrix
5 int minDistance ( int dist [] , bool sptSet []) {
6 int min = INT_MAX , min_index ;
7 for ( int v = 0; v < nover ; v ++)
8 if ( sptSet [ v ] == false && dist [ v ] <= min )
9 min = dist [ v ] , min_index = v ;
10 return min_index ;
11 }
12 }
Choose the appropriate code snippets for the blanks in the following code to complete the
implementation of Dijkstra’s algorithm:
1 void dijkstra ( int src ) {
2 int dist [ nover ];
3 bool sptSet [ nover ];
4 for ( int i = 0; i < nover ; i ++)
5 dist [ i ] = INT_MAX , sptSet [ i ] = false ;
6 dist [ src ] = 0;
7 for ( int count = 0; count < /* Code1 */ ; count ++) {
8 int u = minDistance ( dist , sptSet ) ;
9 /* Code2 */ = true ;
10 for ( int v = 0; v < nover ; v ++)
11 if (! sptSet [ v ] && dist [ u ] != INT_MAX && /* Code3 */ )
12 dist [ v ] = /* Code4 */ ;
13 }
14 }
Which of the following could be the number of vertices traversed when using the DFS
algorithm to go from vertex A to vertex F (including the visit to vertex F)?
A. 2. B. 6.
C. 5. D. None of the above.
A. 1 2 3 4 5 6. B. 1 3 2 4 5 6. C. 1 3 2 4 6 5. D. 3 2 4 1 6 5.
Question 96. Let G be a graph with n vertices and m edges. What is the tightest up-
per bound on the running time on Depth First Search of G? Assume that the graph is
represented using adjacency matrix.
A. O(n). B. O(m + n). C. O(n2 ). D. O(mn).
Question 97. In a depth-first traversal of a graph G with n vertices, k edges are marked
as tree edges. The number of connected components in G is
A. k. B. k + 1. C. n - k - 1. D. n - k.
Question 98. To implement Dijkstra’s shortest path algorithm on unweighted graphs so
that it runs in linear time, the data structure to be used is:
A. Queue. B. Stack. C. Heap. D. B-Tree.
Use for next 3 questions:
Given the Graph class implemented using an adjacency matrix as follows. Choose the
appropriate code snippets for the blanks in the following code to complete the implemen-
tation of Depth-First Search Algorithm:
1 class Graph {
2 private :
3 int V ; // number of vertices
4 int ** adj ; // adjacency matrix
5
6 protected :
7 void DFSRec ( int ** adj , bool visited [] , int s ) {
8 // Code 1
9
10 cout << s << " " ;
11
12 for ( int i = 0; i < V ; i ++) {
13 if ( /* Code 2 */ )
14 /* Code 3 */
15 }
16 }
17 public :
18 void DFS ( int s ) {
19 bool visited [ V ];
20 for ( int v : visited ) visited [ v ] = false ;
21 DFSRec ( adj , visited , s ) ;
22 }
23 };
Which one of the following is NOT the sequence of edges added to the minimum
spanning tree using Kruskal’s algorithm?
A. (b,e)(e,f)(a,c)(b,c)(f,g)(c,d). B. (b,e)(e,f)(a,c)(f,g)(b,c)(c,d).
C. (b,e)(a,c)(e,f)(b,c)(f,g)(c,d). D. (b,e)(e,f)(b,c)(a,c)(f,g)(c,d).
Question 103. Let G be connected undirected graph of 100 vertices and 300 edges. The
weight of a minimum spanning tree of G is 500. When the weight of each edge of G is
increased by five, the weight of a minimum spanning tree becomes
A. 1000. B. 995. C. 2000. D. 1995.
Use for next 4 questions:
Given the Graph class implemented using an adjacency matrix as follows. Choose the
appropriate code snippets for the blanks in the following code to complete the implemen-
tation of Prim’s Algorithm for Minimum Spanning Tree (MST):
1 class Graph {
2 private :
3 int V ; // number of vertices
4 int ** adj ; // adjacency matrix
5
6 protected :
7 int minKey ( int key [] , bool mstSet []) {
8 int min = INT_MAX , min_index ;
9 for ( int v = 0; v < V ; v ++)
10 if ( mstSet [ v ] == false && key [ v ] < min )
11 min = key [ v ] , min_index = v ;
12
13 return min_index ;
14 }
15 public :
16 void primMST () {
17 int parent [ V ];
18 int key [ V ];
19 bool mstSet [ V ];
20 for ( int i = 0; i < V ; i ++)
21 key [ i ] = INT_MAX , mstSet [ i ] = false ;
22 /* Code 1 */
23 // ( a )
24 // ( b )
25 for ( int i = 0; i < V - 1; i ++) {
26 int u = minKey ( key , mstSet ) ;
27 /* Code 2 */
28 for ( int v = 0; v < V ; v ++)
29 if ( adj [ u ][ v ] && mstSet [ v ] == false
30 && /* Code 3 */ )
31 /* Code 4 */
32 }
33 printMST ( parent ) ;
34 }
35 };
Choose the appropriate code to fill in the blanks in checkNode function so that the
isComplete function can determine whether the binary tree with the root node root is
a complete binary tree
1 template < typename E >
2 bool checkNode ( BNode <E > * node , bool & flag , Queue < BNode <E > > & q ) {
3 if ( node ) {
4 if ( /* Code1 */ ) return false ;
5 /* Code2 */
6 } else flag = true ;
7 return true ;
8 }
9 template < typename E >
10 bool isComplete ( BNode <E > * root ) {
11 if ( root == nullptr ) return true ;
12 Queue < BNode <E > * > q ;
13 q . push ( root ) ;
14 bool flag = false ;
15 while (! q . empty () ) {
16 BNode <E > * temp = q . front () ;
17 q . pop () ;
18 if (! checkNode ( temp - > left () , flag , q ) )
19 return false ;
20 if (! checkNode ( temp - > right () , flag , q ) )
21 return false ;
22 }
Question 113 (F-231). How can you check if a binary tree is a binary search tree
(BST)?
A. Perform a pre-order traversal and check if the result is sorted.
B. Perform an in-order traversal and check if the result is sorted.
C. Perform a post-order traversal and check if the result is sorted.
D. Perform a breadth-first traversal and check if the result is sorted.
Question 114 (F-231). Choose the correct implementation of the prtln function for
printing a binary tree using in-order traversal:
A. if (root != NULL) { cout « root->data; prtIn(root->left);
prtIn(root->right); }.
B. if (root != NULL) { cout « root->data; prtIn(root->right);
prtIn(root->left); }.
C. if (root != NULL) { prtIn(root->left); cout « root->data;
prtIn(root->right); }.
D. if (root != NULL) { prtIn(root->right); prtIn(root->left); cout «
root->data; }.
Question 115 (F-231). In Binary Search Tree, the pre-order traversal is:
A. Node - Left - Right. B. Left - Node - Right.
C. Right - Node - Left. D. Right - Left - Node.
Question 116 (F-231). Given a function to insert a node into a binary search tree,
return the root of the tree:
1 TreeNode * bstInsert ( TreeNode * root , int val ) {
2 if ( root == nullptr ) {
3 return new TreeNode ( val ) ;
4 }
5 TreeNode * curr = root ;
6 TreeNode * prev = nullptr ;
7 while ( curr != nullptr ) {
8 prev = curr ;
9 // Code
10 }
11 if ( val < prev - > val ) {
12 prev - > left = new TreeNode ( val ) ;
13 } else {
14 prev - > right = new TreeNode ( val ) ;
15 }
16 return root ;
17 }
Duplicates are not allowed in the tree. Fill in Code to complete the above function.
A. if (val < curr->val) curr = curr->left; else curr = curr->right;.
B. if (val < curr->val) curr = curr->left; else if (val > curr->val)
curr = curr->right; else break;.
C. if (val < curr->val) curr = curr->left; else if (val > curr->val)
curr = curr->right;.
D. if (val < curr->val) curr = curr->left; else if (val > curr->val)
curr = curr->right; else return root;.
Question 117 (F-231). In a binary tree, the depth of a node is
A. The number of direct child nodes of that node.
B. The number of direct parent nodes of that node.
C. The number of direct and indirect child nodes of that node.
Fill in Code comment to complete the function to return the number of leaf in Binary
Tree:
A. if(!root->left && !root->right) return 1;.
B. if(!root->left || !root->right) return 1;.
C. if(!root->left && !root->right) return 0;.
D. if(!root->left || !root->right) return 0;.
Question 121 (F-231). Suppose the numbers 7, 5, 1, 8, 3, 6, 0, 9, 4, 2 are inserted into
an initially empty binary search tree (BST) in the given order. The binary search tree
uses the standard order on natural numbers. What is the result of an in-order traversal
of the tree?
A. 0 1 2 3 4 5 6 7 8 9. B. 0 2 4 3 1 6 5 9 8 7.
C. 7 5 1 0 3 2 4 6 8 9. D. 9 8 6 4 2 3 0 1 5 7.
Question 122 (F-221). The in-order traversal of a binary tree results in (A, B, C, D,
E, F, G), and the post-order traversal results in (B, D, C, A, F, G, E). How many nodes
are there in the right subtree of the root node?
A. 2. B. 3. C. 4. D. 5.
Question 123 (F-221). Given that the pre-order traversal of a binary tree results in
(A, B, C, D, E, K, F, G), and the in-order traversal results in (B, C, A, D, K, E, F, G),
what is the result of the post-order traversal?
A. C, B, K, G, F, E, D, A. B. C, B, K, G, E, F, D, A.
C. C, B, G, K, F, E, D, A. D. All three answers are incorrect.
Question 124. Given that the preorder and postorder traversals of a binary tree produce
the reverse order of elements, for example, preorder is (A, B, C, D) and postorder is (D,
C, B, A), which of the following statements is most accurate?
A. Any node has no left subtree.
B. Any node has no right subtree.
Fill in the blanks to complete the function that calculates the height of a binary tree from
the root node.
Question 125 (F-221). Fill in Code 1:
A. if(pRoot == nullptr) return 0;. B. if(pRoot == nullptr) return 1;.
C. if(pRoot != nullptr) return 0;. D. if(pRoot != nullptr) return 1;.
Question 126 (F-221). Fill in Code 2:
A. return 1 + max(height(pRoot->left()), height(pRoot->right()));.
B. return max(height(pRoot->left()), height(pRoot->right()));.
C. return 1 + min(height(pRoot->left()), height(pRoot->right()));.
D. return min(height(pRoot->left()), height(pRoot->right()));.
Assume that the type E supports the > and < comparison operations. The isBST function
returns true when the root is the root of a binary search tree and false otherwise. Please
fill in the blanks in the checkBST function so that the isBST function works correctly as
described.
1 template < typename E >
2 bool checkBST ( BinNode <E >* pRoot , BinNode <E >* pLeft = nullptr ,
BinNode <E >* pRight = nullptr ) {
3 if (! pRoot ) return true ;
4 if ( pLeft && /* ( a ) */ ) return false ;
5 if ( pRight && /* ( b ) */ ) return false ;
6 return /* ( c ) */ ;
7 }
8 template < typename E >
9 bool isBST ( BinNode <E >* pRoot ) {
10 return checkBST ( pRoot ) ;
11 }
3. All nodes (except leaf nodes) in a tree have an out-degree greater than or equal to 1.
4. In a binary tree, if the height of the tree is 4, then the number of nodes in the tree
is 15.
Question 137. While inserting the elements 71, 65, 84, 69, 67, 83 in an empty binary
search tree (BST) in the sequence shown, the element in the lowest level is
A. 65. B. 67. C. 69. D. 83.
Question 138. What does the following function do for a given binary tree?
1 int fun ( Node * root )
2 {
3 if ( root == NULL )
4 return 0;
5 if ( root - > left == NULL && root - > right == NULL )
6 return 0;
7 return 1 + fun ( root - > left ) + fun ( root - > right ) ;
8 }
Choose the appropriate code to fill in the blank in deleteNode method to delete a node
from BST. Given the function minValueNode as helper function below:
1 Node * minValueNode ( Node * node ) {
2 Node * current = node ;
3 while ( current && current - > pLeft != nullptr )
4 current = current - > left ;
5 return current ;
6 }
7
8 Node * deleteNode ( Node * root , T value ) {
9 if ( root == nullptr ) return root ;
10 if ( value < pLeft - > value )
11 /* Code 1 */
12 else if ( value > pLeft - > value )
13 /* Code 2 */
14 else
15 {
16 if ( root - > pLeft == nullptr )
17 {
18 Node * temp = root - > pRight ;
19 delete root ;
20 return temp ;
21 }
22 else if ( root - > pRight == nullptr )
23 {
24 Node * temp = root - > pRight ;
25 delete root ;
26 return temp ;
27 }
28
29 Node * succ = /* Code 3 */
30 root - > value = succ - > value ;
31 /* Code 4 */
32 root - > pRight = deleteNode ( root - > pRight , value ) ;
33 }
34 return root ;
35 }
A. rotateLeft(subroot). B. rotateLeft(subroot->pLeft).
C. rotateRight(subroot). D. rotateRight(root).
Question 145 (F-231). Insert the values 8, 2, 12, 3, 4, and 7 into an empty AVL tree
one by one. What is the result of the postorder traversal of the tree?
A. 2 3 7 12 8 4. B. 2 3 4 7 8 12. C. 3 2 4 8 7 12. D. 4 3 2 8 7 12.
Question 146 (F-231). Insert the values 2, 8, 12, 3, and 4 into an empty AVL tree one
by one. What will be the result of the preorder traversal of the tree?
A. 8 2 3 4 12. B. 2 4 3 12 8. C. 8 3 12 2 4. D. 8 3 2 4 12.
Question 147 (F-231). What is the maximum height difference between leaves in an
AVL tree?
A. 0 or 1.
B. At most 1.
C. n, where n is the number of nodes.
D. log(n), where n is the number of nodes.
Question 148 (F-231). What are the disadvantages of using a Splay tree?
A. Splay operation is complicated.
B. No significant disadvantages.
C. Splay tree performs unnecessary splay steps when a node is accessed.
D. The height of the splay tree can become linear when accessing elements in ascending
order.
Question 149 (F-231). Given the following Splay tree:
A.
.
B.
.
C.
.
D.
.
Question 150 (F-231). What is the worst-case time complexity when inserting n2 ele-
ments into an AVL tree that initially has n elements?
A. O(n log(n)). B. O(n2 log(n)). C. O(n3 ). D. O(n3 log(n)).
Question 151 (F-231). Insert the following keys into an empty B-Tree (m = 3): 50,
40, 70, 55, 45, 43, 56, 58. How many nodes in the resulting tree have more than one
entry?
A. 0. B. 1. C. 2. D. 3.
Question 152 (F-231). Given an AVL tree as shown, determine the preorder traversal
of the AVL tree after deleting the key 13.
A. 20 15 25 22 40 30. B. 20 25 15 40 22 30.
C. 25 20 15 22 40 30. D. 25 20 22 15 40 30.
Question 153 (F-231). Given an AVLTree as described in the experiments, complete
the code to insert multiple elements (in order) from an array into the AVL tree:
1 AVLTree < int > avl ;
2 int arr [] = {20 , 18 , 40 , 4 , 5 , 50 , 17 , 28};
3 for ( int i = 0; i < 8; i ++) {
4 ______________________ ;
5 }
A. avl.insert(arr[i]). B. avl->insert(arr[i]).
C. *avl.insert(arr[i]). D. (*avl)->insert(arr[i]).
Question 154 (F-231). What is the maximum height of an AVL tree with p nodes?
A. p. B. p/2. C. log(p). D. log(p)/2.
Question 155 (F-221). Given an AVL tree with two nodes, where the root node has
a value of 15 and the other node has a value of 20. When a node with a value of 19 is
inserted, what action needs to be taken?
A. Perform a single left rotation. B. Perform a single right rotation.
C. Perform a double rotation. D. No rotation is needed.
Question 156 (F-221). Construct a B-Tree of order 3 from the following sequence of
keys: (18, 4, 2, 46, 48, 29, 30). Which of the following keys, when inserted into the B-tree,
will cause a node split?
A. 1, 32, 53. B. 1, 19, 20. C. 1, 19, 32. D. 1, 19, 32, 53.
Question 157 (F-221). Which of the following statements about an m-degree B-Tree
is NOT correct?
A. The root node has at most m children.
B. All leaf nodes are at the same level.
C. The keys in the root node are sorted in order.
D. An internal node has at least m2 + 1 non-empty children (if m is even) or m2 − 1
non-empty children (if m is odd).
Question 158 (F-221). Insert the following numbers into an empty AVL tree: 3, 10, 20,
9, 1, 5. List the nodes at level 2 in the final tree in ascending order.
A. 3, 5, 20. B. 3, 10. C. 1, 5, 20. D. 3, 5, 10.
Question 159 (F-221). Given an AVL tree with the preorder traversal result as (13,
10, 5, 4, 6, 11, 15, 16) and the inorder traversal result as (4, 5, 6, 10, 11, 13, 15, 16),
after inserting a node with the value 7 into the tree, what will be the preorder traversal
result?
A. 13, 5, 4, 6, 10, 7, 11, 15, 16. B. 13, 6, 5, 4, 10, 7, 11, 15, 16.
C. 6, 13, 5, 4, 10, 7, 11, 15, 16. D. 6, 5, 4, 10, 7, 11, 13, 15, 16.
Question 160 (F-221). Insert the following numbers into an empty AVL tree: 50, 23,
70, 19, 29, 65, 83, 25, 35, 53. After all insertions, delete the numbers 19, 23, and 83 from
the AVL tree. List the nodes at level 2 in the final tree in left-to-right order.
A. 25, 29, 50, 70. B. 25, 35, 53, 70. C. 25, 50, 53, 70. D. 29, 35, 65, 70.
Question 161 (F-221). A B-Tree of order m = 4 and height 4, what is the maximum
number of entries it can have?
A. 255. B. 160. C. 127. D. 64.
Question 162 (F-221). Which of the following statements about AVL trees is FALSE?
A. Only i) and iii) are correct. B. Only i) and ii) are correct.
C. Only ii) and iii) are correct. D. All three statements are correct.
Question 164 (F-221). For an AVL tree, the balance factor (the difference in height
between the left and right subtrees) at each node is within the range of:
A. [0, 1]. B. [-1, 1]. C. [1, 2]. D. [-2, 2].
Question 165 (F-211). The AVL tree is presented in a list format as follows:
67(51(47(44,N),56(N,63)),71(69,82(73,86))), where N represents NULL. Insert the nodes
79 and 68 into the AVL tree. What is the sum of the keys at the leaf nodes after the
insertion?
A. 367. B. 411. C. 245. D. 157.
Question 166 (F-211). Insert the following numbers into a B-Tree of order m = 3: 46,
99, 25, 60, 48, 15, 92, 57, 93, 45. What is the height of the tree after the insertions?
A. 4. B. 3. C. 2. D. 5.
Question 167 (F-211). Given a B-Tree with m = 5, after deleting the key 57 from the
tree, what are the keys in the parent node of the node containing key 84?
A. 70, 76, 98. B. 60, 76, 98. C. 60, 70, 76. D. 60, 70, 98.
Question 168 (F-211). Given an AVL tree represented as:
44(38(31(27,34), 41(39,N)), 109(89, 114)), where N is NULL. After deleting the nodes 109
and 89 from the tree (always choosing the largest node from the left subtree), what is the
sum of the keys at levels 0 and 1?
A. 113. B. 456. C. 278. D. 398.
Question 169 (F-211). Given a splay tree represented as: 30(29,31(N,32(N,35))), where
N is NULL. After adding 37 and 33 to the splay tree, what is the number of nodes at
level 2?
Question 170 (F-191). What is a splay operation?
A. Move a node to become the root.
B. Move a parent node down to become a child.
C. Move the root node down to become a leaf.
D. Delete a leaf node from the tree.
Question 171 (F-191). After sequentially inserting the elements 7, 15, 6, 16, 9, 11, and
4 into an empty splay tree, the height of the tree will depend on the splay operations
performed after each insertion.
A. 4. B. 5. C. 3. D. 6.
Question 172 (F-191). Insert the following integers sequentially into an empty AVL
tree: 2, 1, 4, 5, 9, 3, 6, 7. What will be the preorder traversal (NLR) of the tree?
A. 4 2 1 3 6 5 9 7. B. 1 3 2 5 7 9 6 4. C. 4 2 1 3 6 9 5 7. D. 1 3 4 2 5 9 6 7.
Question 173 (F-191). Given an AVL tree with the preorder traversal as 50, 40, 30, 10,
45, 60, 55, after deleting the element 50 (always replacing it with the largest element from
the left subtree), what is the sum of the values of the nodes at level 2 in the tree?
A. 105. B. 100. C. 55. D. 70.
Question 174. Given an empty AVL tree, how would you construct AVL tree when a
set of numbers are given without performing any rotations?
A. Just build the tree with the given input.
B. Find the median of the set of elements given, make it as root and construct the tree.
C. Use trial and error.
D. Use dynamic programming to build the tree.
Question 175. Consider the below left-left rotation pseudo code where the node contains
value pointers to left, right child nodes and a height value and Height() function returns
height value stored at a particular node.
1 AVLTree leftrotation ( AVLTreeNode z ) :
2 AVLTreeNode w =x - > left
3 x - > left =w - > right
4 w - > right = x
5 x - > height = max ( Height (x - > left ) , Height (x - > right ) ) +1
6 w - > height = max ( /* missing */ ) +1
7 return w
Dựa vào các yêu cầu trên, cấu trúc dữ liệu nào sẽ phù hợp hơn?
A. XArrayList vì có thể truy cập ngẫu nhiên nhanh và đảm bảo hiệu suất cache.
B. DLinkedList vì thao tác thêm/xóa nhanh và không tốn resize.
C. xMap vì có thể truy cập dễ dàng theo key.
D. Heap vì dễ dàng duy trì các record.
Dữ liệu sau đây được sử dụng cho 4 câu hỏi bên dưới:
Lớp DataLoader được khai báo với các thuộc tính và phương thức như bên dưới. Trong
đó các thuộc tính:
• dataset: Mảng chứa dữ liệu gốc (sử dụng XArrayList<T> để tận dụng các thao tác
sử dụng trong BTL).
• indices: Mảng chứa các chỉ số, được dùng để thực hiện xáo trộn dữ liệu (shuffle)
nếu cần.
• seed: dùng để thực hiện tạo hạt giống để xáo trộn ngẫu nhiên nếu cần.
11 public :
12 // Constructor
13 DataLoader ( const XArrayList <T >& data , int batchSize , int batchSize ,
bool shuffle , int seed ) ;
14
15 bool hasNext () ;
16 XArrayList <T > getBatch () ;
17 void reset () ;
18 int size () ;
19 protected :
20 void shuffleIndices () ;
21 };
Question 182. Xét constructor cần hoàn thiện của DataLoader, với tham số đầu vào là
Dataset gốc cần load data và kích thước của mỗi batch khi load dữ liệu batchSize:
1 template < class T >
2 DataLoader <T >:: DataLoader ( const XArrayList <T >& data , int batchSize ,
bool shuffle , int seed ) {
3 this - > dataset = data ;
4 this - > batchSize = batchSize ;
5 this - > currentIndex = 0;
6 this - > shuffle = shuffle ;
7 this - > seed = seed ;
8 // TODO (1)
9 // TODO (2)
10 this - > shuffleIndices () ; // Use for shuffle dataset
11 }
Đoạn code phù hợp cần điền vào dòng TODO (1) để khởi tạo thuộc tính indices là:
A. for(int i = 0; i < data.size(); i++) indices.add(i);.
B. indices.resize(data.size());.
C. indices = new int[data.size()];.
D. indices.reserve(data.size());.
Question 183. Xét constructor như trong câu trên, đoạn code phù hợp cần điền vào
dòng TODO (2) để khởi tạo thuộc tính dataset là:
A. this->dataset = data;.
B. this->dataset.copyFrom(data);.
C. for(int i = 0; i < data.size(); i++) this->dataset.add(data.get(i));.
D. this->dataset = XArrayList<T>(data);.
Question 184. Trong quá trình huấn luyện mô hình, DataLoader cần kiểm tra xem
còn batch dữ liệu tiếp theo không thông qua phương thức hasNext(). Xét phương thức
hasNext() cần thực hiện như bên dưới:
1 template < class T >
2 bool DataLoader <T >:: hasNext () {
3 // TODO
4 }
Để kiểm tra còn đủ phần tử cho một batch tiếp theo hay không và trả về true nếu còn đủ
phần tử, false nếu ngược lại. Dòng code nào sau đây phù hợp để điền vào vị trí TODO?
A. return currentIndex < dataset.size();.
B. return !dataset.empty();.
C. return currentIndex + batchSize <= dataset.size();.
D. return dataset.size() > 0;.
Question 185. Trong quá trình huấn luyện mô hình, phương thức getBatch() có nhiệm
vụ lấy ra một batch dữ liệu tiếp theo để huấn luyện. Xét phương thức getBatch() cần
hoàn thiện như bên dưới:
1 template < class T >
2 XArrayList <T > DataLoader <T >:: getBatch () {
3 if ( /* ( a ) */ ) throw std :: runtime_error ( " No more batch " ) ;
4 XArrayList <T > batch ;
5 // ( b )
6 currentIndex += batchSize ;
7 return batch ;
8 }
Điều kiện logic và dòng code nào sau đây là phù hợp để điền vào các vị trí (a) và (b) theo
thứ tự:
A. (a): hasNext() ; (b): batch = dataset.subList(currentIndex,
currentIndex + batchSize);.
B. (a): !hasNext() ; (b): for(int i = currentIndex; i < currentIndex +
batchSize; i++) batch.add(dataset.get(indices[i]));.
C. (a): !hasNext() ; (b): for(int i = 0; i < batchSize; i++)
batch.add(dataset.get(i));.
D. (a): !hasNext() ; (b): memcpy(batch.data, dataset.data +
currentIndex, batchSize * sizeof(T));.
Dữ liệu sau đây được sử dụng cho 2 câu hỏi bên dưới:
Nhằm hỗ trợ cho quá trình huấn luyện mô hình trong machine learning, lớp TensorDataset
được thiết kế kế thừa từ Dataset với mục đích quản lý cặp dữ liệu bao gồm dữ liệu đầu
vào và nhãn tương ứng của nó. Các khai báo ban đầu, bao gồm các thuộc tính và phương
thức được cho như bên dưới:
1 template < typename DType , typename LType >
2 class TensorDataset {
3 protected :
4 DLinkedList < DType > data ;
5 DLinkedList < LType > label ;
6 int size ;
7 public :
8 TensorDataset ( const DLinkedList < DType >& data , const
DLinkedList < LType >& label ) ;
9 std :: pair < DType & , LType & > get ( int index ) ;
10 int getSize () ;
11 void shuffle () ;
12 }
Cho các đoạn code sau đây (được đánh dấu bởi các vị trí (a), (b), (c), (d):
1 /* - - - - - - - - - - - - - - - - - - - - ( a ) - - - - - - - - - - - - - - - - - - - - - */
2 this - > data = data ;
3 this - > label = label ;
4 this - > size = data . size () ;
5 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
6
7 /* - - - - - - - - - - - - - - - - - - - - ( b ) - - - - - - - - - - - - - - - - - - - - - */
8 if ( data . size () != label . size () )
9 throw std :: invalid_argument ( " Data and label must have same size " ) ;
10 this - > data = data ;
11 this - > label = label ;
12 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
13
14 /* - - - - - - - - - - - - - - - - - - - - ( c ) - - - - - - - - - - - - - - - - - - - - - */
15 if ( data . size () != label . size () )
16 throw std :: invalid_argument ( " Data and label must have same size " ) ;
17 for ( int i = 0; i < data . size () ; i ++) {
18 this - > data . add ( data . get ( i ) ) ;
19 this - > label . add ( label . get ( i ) ) ;
20 }
21 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
22
23 /* - - - - - - - - - - - - - - - - - - - - ( d ) - - - - - - - - - - - - - - - - - - - - - */
24 try {
25 for ( int i = 0; i < data . size () ; i ++) {
26 this - > data . add ( data . get ( i ) ) ;
27 this - > label . add ( label . get ( i ) ) ;
28 }
29 } catch (...) {
30 throw std :: invalid_argument ( " Error copying data " ) ;
31 }
32 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
Trong các đoạn code trên, có bao nhiêu đoạn phù hợp để điền vào vị trí TODO đảm bảo
quá trình khởi tạo không thể gây ra lỗi ngoài mong muốn?
A. 1. B. 2. C. 3. D. 4.
Question 187. Phương thức get() dùng để lấy cặp data, label tương ứng tại vị trí
index. Phương thức được triển khai như sau:
1 std :: pair < DType & , LType & > TensorDataset < DType , LType >:: get ( int index ) {
2 // TODO
3 }
9 // - - - - - - - - - - - - - - - - - ( C ) - - - - - - - - - - - - - - - - - - - - - - - - //
10 try {
11 return std :: pair < DType , LType >( data . get ( index ) , label . get ( index ) ) ;
12 } catch (...) {
13 throw std :: out_of_range ( " Invalid index " ) ;
14 }
15
16 // - - - - - - - - - - - - - - - - - ( D ) - - - - - - - - - - - - - - - - - - - - - - - - //
17 if ( index >= 0 && index < data . size () )
18 return std :: pair < DType , LType >( data . get ( index ) , label . get ( index ) ) ;
19 return DataLabel < DType , LType >() ;
41
42 /* ============= ( b ) ====== ======== === */
43
44 /* ============= ( c ) ====== ======== === */
45
46 return retDL ;
47 }
48 // Another attributes override from Dataset ...
49 };
Trong đó:
Các thuộc tính:
• image_paths, labels: Đường dẫn đến các tệp tin ảnh và nhãn tương ứng với mỗi
ảnh. (đều có kiểu DLinkedList để sử dụng các thao tác đã phát triển từ BTL)
• read_image: dùng để đọc và xử lý ảnh từ tệp tin (với tham số truyền vào là chuỗi
đường dẫn).
• len: dẫn xuất từ class Dataset, dùng để trả về kích thước của tập dữ liệu.
• getitem: dẫn xuất từ class Dataset, dùng để trả về dữ liệu ảnh và nhãn tương ứng
tại vị trí index có kiểu DataLabel.
Question 188. Điều kiện rẽ nhánh cần điền tại dòng comment (a) là:
A. if(index < 0 && index >= len()).
B. if(index < 0 || index > len()).
C. if(index < 0 || index >= len()).
D. if(index == 0 || index == len()).
Question 189. Trong trường hợp dữ liệu ảnh không chứa nhãn tương ứng, ta chỉ trả về
dữ liệu của tập tin ảnh, còn nhãn thì không. Đoạn lệnh phù hợp với yêu cầu tại dòng
comment (b) là:
A. if(labels.empty()) return image_paths.get(index);.
B. if(labels.empty()) return DataLabel<DType, LType>(image_paths.get(index),
DLinkedList<LType>());.
C. if(!labels.empty())
return DataLabel<DType, LType>(read_image(image_paths.get(index)),
DLinkedList<LType>());.
D. if(labels.empty())
return DataLabel<DType, LType>(read_image(image_paths.get(index)),
DLinkedList<LType>());.
Question 190. Trong trường hợp dữ liệu ảnh chứa cả đường dẫn và nhãn tương ứng, ta
cần trả về cả dữ liệu của ảnh và nhãn tại vị trí index. Đoạn lệnh phù hợp với yêu cầu tại
dòng comment (c) là:
A. if(image_paths.size() > 0 && labels.size() > 0 && image_paths.size()
== labels.size())
return DataLabel<DType, LType>(read_image(image_paths.get(index)),
DLinkedList<LType>(labels.get(index)));.
• int (*comparator)(T& lhs, T& rhs): Con trỏ hàm so sánh hai phần tử kiểu T để
xác định thứ tự của chúng trong heap.
Question 195. Cho phương thức reHeapUp để thực hiện sắp xếp lại mảng heap đảm bảo
đưa phần tử về đúng vị trí sau khi thêm phần tử đó vào max-heap. Cho hiện thực của
phương thức đó như sau, với elements là mảng chứa các phần tử của Heap:
1 template < class T >
2 void Heap <T >:: reHeapUp ( int position ) {
3 if ( position <= 0) return ;
4 int parent = /* a */
5 while ( position > 0 && /* b */ ) {
Giả sử thuộc tính int (*comparator)(T& lhs, T& rhs) khác NULL. Để Heap<T> là
max heap thì hàm comparator trả về ba giá trị theo quy luật sau:
• +1: nếu lhs < rhs
• -1: nếu lhs > rhs
• 0: trường hợp khác.
Chọn đoạn mã phù hợp để điền vào các comment (a), (b), (c):
A. (a): (parent - 1)/2; (b): comparator(elements[parent],
elements[position]) > 0; (c): (parent - 1)/2;.
B. (a): (parent + 1)/2; (b):comparator(elements[parent],
elements[position]) < 0; (c): (parent - 1)/2;.
C. (a): (parent - 1)/2; (b): comparator(elements[parent],
elements[position]) > 0 (c): (parent + 1)/2;.
D. (a): (parent - 1)/2; (b): comparator(elements[parent],
elements[position]) < 0 (c): (parent - 1)/2;.
Question 196. Khi xóa phần tử gốc trong Heap, phương thức pop sẽ di chuyển phần
tử cuối lên đầu và thực hiện reheapDown để duy trì tính chất heap. Cho hiện thực của
phương thức reheapDown như sau:
1 template < class T >
2 void Heap <T >:: reheapDown ( int position ) {
3 int leftChild = /* ( a ) */
4 int rightChild = /* ( b ) */
5 int target = position ;
6
7 if ( /* ( c ) */ ) target = leftChild ;
8
9 if ( /* ( d ) */ ) target = rightChild ;
10
11 if ( target != position ) {
12 swap ( position , target ) ;
13 reheapDown ( target ) ;
14 }
15 }
Giả sử thuộc tính int (*comparator)(T& lhs, T& rhs) khác NULL. Để Heap<T> là
max heap thì hàm comparator trả về ba giá trị theo quy luật sau:
• +1: nếu lhs < rhs
• -1: nếu lhs > rhs
• 0: trường hợp khác.
Chọn đoạn mã phù hợp để điền vào các comment (a), (b), (c), (d):
A. (a): 2*i + 1; (b): 2*i + 2; (c): leftChild < count &&
comparator(elements[parent], elements[position]) > 0);
(d): rightChild > count && comparator(elements[parent],
elements[position]) > 0);.
Question 197. Cho biết thứ tự topo (topological order) dùng phép duyệt theo chiều sâu
(thứ tự chọn đỉnh theo quy tắc tăng dần):
A. F G H B E D A C. B. H C A E G B F D.
C. C A D E B H G F. D. F G H D B E A C.
Question 198. Cho biết thứ tự topo (topological order) dùng phép duyệt theo chiều
rộng (thứ tự chọn đỉnh theo quy tắc tăng dần):
A. C A D E B H G F. B. C H A D E G B F.
C. F G H D B E A C. D. H C G A E D B F.
Dùng cho các câu hỏi bên dưới: Cho class TopoSorter<T> hỗ trợ việc sắp xếp topo
(Topological Sorting), Class TopoSorter<T> cung cấp hai phương pháp chính để sắp xếp
topo: dfsSort, sử dụng thuật toán tìm kiếm theo chiều sâu (DFS), và bfsSort, sử dụng
thuật toán tìm kiếm theo chiều rộng (BFS), với các mô tả như sau:
• DGraphModel<T>* graph: Con trỏ tới đối tượng đồ thị có hướng (directed graph)
chứa các đỉnh và cạnh được sắp xếp, là cơ sở để thực hiện sắp xếp topo.
• int (*hash_code)(T&, int): Con trỏ tới hàm băm được sử dụng để ánh xạ các
đỉnh của đồ thị thành các giá trị số nguyên.
• Các phương thức còn lại như trong đặc tả của BTL3.
Question 199. Cho phương thức dfsVisit nhằm hỗ trợ cho phương thức dfsSort để
sắp xếp topo theo thuật toán DFS. Hiện thực của phương thức như sau:
1 DLinkedList <T > dfsSort () {
2 DLinkedList <T > result ;
3 DLinkedList <T > vertices = this - > graph - > vertices () ;
4 xMap <T , bool > visited ( this - > hash_code ) ;
5
6 typename DLinkedList <T >:: Iterator it ;
7 // Mark all vertices unvisited
8 for ( it = vertices . begin () ; it != vertices . end () ; it ++)
9 visited . put (* it , false ) ;
10
11 // Get out degree of each vertex in this graph
12 xMap <T , int > outDegree = this - > vertex2outDegree ( this - > hash_code ) ;
13 Stack <T > stack ;
14 // Get zero in - degree vertices of this graph
15 DLinkedList <T > zeroInDegree = this - > l is t O fZ e ro I nD e g re e s () ;
16
17 typename DLinkedList <T >:: Iterator v ;
18 for ( v = zeroInDegree . begin () ; v != zeroInDegree . end () ; v ++)
19 if (! visited . get ( v ) ) this - > dfsVisit (v , visited , stack ) ;
20
21 while (! stack . empty () )
22 result . add ( stack . pop () ) ;
23
24 return result ;
25 }
26 void dfsVisit ( T vertex , xMap <T , bool >& visited , Stack <T >& stack ) {
27 // Mark visited vertice
28 /* ( a ) */
29 visited . put ( vertex , true ) ;
30
31 // Get outward edge of this vertex .
32 DLinkedList <T > outward = this - > graph - > getOutwardEdges ( vertex ) ;
33
34 typename DLinkedList <T >:: Iterator it ;
35 for ( it = outward . begin () ; it != outward . end () ; it ++) {
36 /* ( b ) */
37 if ( /* ( c ) */ ) this - > dfsVisit ( neighbor , visited , stack ) ;
38 }
39
40 stack . push ( vertex ) ;
41 }
Đoạn mã phù hợp trong các comment (a), (b), (c) là:
A. (a): visited.put(vertex, true), (b): T* neighbor = (*it), (c):
!visited.get(neighbor).
B. (a): visited.put(vertex, false), (b): T neighbor = (*it), (c):
visited.get(neighbor).
C. (a): visited.put(vertex, true), (b): T neighbor = (*it), (c):
!visited.get(neighbor).
D. (a): visited.put(vertex, true), (b): T* neighbor = (*it), (c):
!visited.get(neighbor).
Question 200. Hiện thực của phương thức bfsSort như sau:
1 DLinkedList <T > bfsSort ( bool sorted = true ) {
2 DLinkedList <T > result ;
3 // Get in - degree of each vertex in graph
4 xMap <T , int > inDegree = this - > vertex2inDegree ( this - > hash_code ) ;
5
6 Queue <T > queue ;
7 typename DLinkedList <T >:: Iterator it ;
8 for ( it = zeroInDegree . begin () ; it != zeroInDegree . end () ; it ++) {
9 queue . push (* it ) ;
10 }
11
Đoạn mã phù hợp cần điền vào các comment (a), (b) là:
A. (a) inDegree.get(neighbor) - 1, (b): if(newInDegree == 0)
queue.push(neighbor).
B. (a) inDegree.get(neighbor) - 2, (b): if(newInDegree == 1)
queue.push(neighbor).
C. (a) inDegree.get(neighbor) - 2, (b): if(newInDegree == 0)
queue.push(neighbor).
D. (a) inDegree.get(neighbor) - 1, (b): if(newInDegree == 0)
queue.push(neighbor).
1. C 2. B 3. D 4. C 5. B 6. D 7. C 8. A 9. B 11. A
12. B 13. B 14. C 15. C 16. B 17. C 18. D 19. C 20. A 21. C
22. D 23. B 24. B 25. A 26. B 27. B 28. A 29. B 30. C 31. A
32. B 33. B 34. A 35. D 36. D 37. D 38. A 39. C 41. A 43. A
45. A 47. D 48. B 49. C 50. A 51. D 52. C 53. C 54. D 55. A
56. D 57. B 58. C 59. B 60. D 61. B 62. D 63. D 64. A 65. D
66. A 67. A 68. A 69. A 70. B 71. C 72. D 73. B 74. A 75. B
76. C 77. B 78. B 79. D 80. B 81. B 82. B 83. A 84. D 85. C
86. A 87. C 88. B 89. B 90. D 91. C 92. A 93. C 94. D 95. D
96. C 97. B 98. A 99. C 100. C 101. A 102. D 103. B 104. B 105. A
106. A 107. B 108. A 109. C 110. C 111. C 112. A 113. B 114. C 115. A
116. D 117. D 118. D 119. A 120. C 121. A 122. A 123. A 124. C 125. A
126. A 127. A 128. A 129. D 130. A 131. B 132. C 133. A 134. A 135. B
136. B 137. B 139. B 140. C 143. D 144. C 145. A 146. D 6. A 150. A
151. B 152. C 153. A 154. C 155. C 156. B 157. D 158. C 159. B 160. B
161. A 162. C 163. C 164. B 165. B 166. C 167. A 168. A 170. A 171. B
172. A 173. A 174. B 175. A 176. A 177. A 178. D 179. A 180. C 181. A
182. A 183. C 184. C 185. B 186. B 187. C 188. C 189. D 190. A 191. B
192. A 193. C 194. A 195. A 196. C 197. C 198. B 199. C 200. A