PHÂN TÍCH THU T TOÁN
NÂNG CAO
Xét toán sau dùng tìm cách hai nhau trong có n nguyên:
// Output: cách hai trong for to do for to do if and return
Hãy ra cách toán Trình bày toán và ra giá toán
Sau khi xong này sinh viên có
- Thao tác thành các quy
Ký là gian tính toán vào là nguyên n a Xây công quy cho T(n) b Xác giá cho T(n) pháp c mã mã Python
8 return a là nguyên, là nguyên không âm Hay cho hàm công gì? b giá gian tính hàm c mã mã Python
2.2 XÁC NH QUY LU T QUY N P
- , a công quy cho các dãy trên b ngôn Python trình tính các dãy trên pháp quy c ngôn Python trình tính các dãy trên không quy
- tra nguyên n có toàn trình các yêu trên pháp quy và không quy
Ví hàm quy tính dãy quy: def S(n): if n==1: return 1 else: return 1/n+S(n-1)
Không quy quy) def S(n): sum = 0 for i in range(1,n+1): sum+=1/i return sum
DANH SÁCH LIÊN K T - P - I
Danh sách liên k t và l ng
Cho SinhVien có các tính sau:
DSSV là danh sách liên kết các sinh viên, cho phép thêm sinh viên vào vị trí X, in ra toàn bộ thông tin sinh viên, và xóa sinh viên tại vị trí X Ngoài ra, có thể tìm kiếm thông tin sinh viên theo họ tên và xóa toàn bộ danh sách DSSV khi cần thiết.
Stack Creation pop push top isEmpty
Mã Python cho hoàn class Stack: def init (self): self.items = [] def pop(self): def push(self,item): def top(self): def isEmpty(self): return len(self.items) == 0
Sinh viên hoàn thành các th c còn thi u và vi t th c main v i các g i ý sau:
N u Stack r ng s in ra ngo i l ng h p Stack không r ng thì Node cu i cùng vào m t bi n, xóa Node kh i Stack và return bi n
N u Stack r ng s in ra ngo i l ng h p Stack không r ng thì tr ra Node v trí
- th c : t th c (ho c s d ng ph th c) c a danh sách liên k t
- th c : Tr v k t qu so sánh s ng Node v i
Mô Cho là Hãy tìm
Chia bài toán thành 2 giai
10 qua : phân sang , chia cho là ký cùng vào sau phép chia chia cho , là ký t sát ký cùng cho khi 0, cùng trong ra
2 Ký pháp trung trung (infix) (prefix) (Postfix)
Infix Prefix Postfix x+y +xy xy+ x+y-z -+xyz xy+z x+y*z +x*yz xyz*+ x+(y-z) +x-yz xyz-+
16 BÀI 3: - - trung qua kí trong trung trái qua kí thi sau:
- là ) toán trong vào output cho khi ( ra
Toán x có tiên toán thì toán ra và vào output toán vào
- Sau khi trung trong thì kí trong và cho vào output
Ch trung trong trung trái qua sau:
- là ( n toán trong vào output cho khi ) ra
Toán có tiên toán thì toán ra và vào output toán vào
- Sau khi trung trong thì các kí trong vào output cùng thu
3 quy quy chính là chính Do khi hàm quy thì máy tính phát vùng có
Stack hoạt động theo mô hình LIFO (last in first out), nghĩa là phần tử được thêm vào sau sẽ được lấy ra trước Quá trình này diễn ra thông qua các trình con trong quy trình chính, trong đó trình con có thể gọi chính nó Khi trình con hoàn tất, chúng ta có thể nói rằng nó đã quay trở lại.
Khi trình con vào thì các và mã xong này là
Khi quay các giá và sau dùng Tính này cho phép dùng stack l các giá trình con các tham khi thì các giá ra Các có tóm sau:
- 2: các tham hình 1 vào stack
2 X qui (NEO) thì lý qui) lý theo toán
Xác quy các tham và các tham vào stack
Bài : Xây bài toán tháp Hà pháp quy stack
Queue Creation dequeue enqueue front isEmpty
The provided Python code defines a class named `Queue`, which implements a basic queue data structure It includes an initializer method that creates an empty list to store items and sets the front index to zero The class features methods for adding items to the queue (`enqueue`), removing items from the front (`dequeue`), and checking the front item (`front`), with error handling for accessing the front of an empty queue Additionally, it includes a method to check if the queue is empty.
Sinh viên hoàn thành các th c còn thi u và vi t th c main v i các g i ý sau:
N u Queue r ng s in ra ngo i l
BÀI 3: T - - 19 ng h p Queue không r ng thì Node u tiên vào m t bi n, xóa Node kh i Queue và return bi n
N u Queue r ng s in ra ngo i l ng h p Queue không r ng thì tr ra Node trên cùng
- th c : t th c (ho c s d ng th c) append c a danh sách liên k t
- th c : Tr v k t qu so sánh s ng Node v i
Bài toán hàng: nhà hàng lý DonHang các tính sau:
- SDTNguoiDat a DH thông tin trên b DSDH danh sách DonHang c thêm DonHang vào danh sách d DonHang danh sách e xóa toàn DSDH
Sau khi xong này sinh viên có
- các trúc cây phân tìm
- Cài trúc cây phân tìm
4.1 CÂY NH PHÂN TÌM KI M
Cây phân tìm Node, Node là class các thành
- và và và cây phân tìm class Node và các
P
The Python code for declaring a Binary Search Tree (BST) includes a class definition for `BinarySearchTree` and a nested class ` Node` The ` Node` class has an initializer that sets the value, left, and right children of the node It provides methods to get and set the value, left child, and right child The `BinarySearchTree` class initializes with a root set to None and includes methods for inserting, searching, deleting nodes, and performing pre-order, in-order, and post-order traversals.
Sinh viên hoàn thành các còn các ý sau:
Giá chèn vào cây là một yếu tố quan trọng, với tên gọi là quy Bên trong, giá chèn và nút có mối liên hệ chặt chẽ Giá của nút có ảnh hưởng đến giá trị tổng thể Quy tham gia vào nút bên và giá, cũng như nút bên trái và giá, tạo nên sự liên kết giữa các thành phần trong cấu trúc.
CÂY NH PHÂN TÌM KI M
NÂNG CAO
Sinh viên tìm và cài các trúc sau:
Sau khi xong này sinh viên có
- và phân tích các toán
- Cài các toán theo khóa
5.1 SELECTION SORT Ý có tên có tác tìm TRÍ có giá trong yêu def select(seq, start): minIndex = start for i in range(start + 1, len(seq)): if seq[minIndex] > seq[i]: minIndex = i return minIndex có tên tiên danh sách giá index select trên: def selectionSort(seq): for i in range(len(seq)-1): minIndex = select(seq, i) tmp = seq[i] seq[i] = seq[minIndex] seq[minIndex] = tmp
Trong là danh sách vào
5.2 BUBBLE SORT Ý ( hai nhau sai trí thì chúng nhau.
THU T TOÁN S P X P
SELECTION SORT
The article discusses a selection sort algorithm implemented in Python It defines a function called `select` that finds the index of the minimum value in a sequence starting from a given index The `selectionSort` function utilizes this `select` function to sort the entire sequence by repeatedly finding the minimum value and swapping it with the current position This method effectively organizes the list in ascending order.
Trong là danh sách vào
BUBBLE SORT
Ý ( hai nhau sai trí thì chúng nhau
BÀI 5: 29 def bubbleSort(seq): for i in range(len(seq) - 1): for j in range(0, len(seq) - i - 1): if seq[j] < seq[j + 1]: seq[j], seq[j + 1] = seq[j + 1], seq[j]
INSERTION SORT
Ý Tìm các không và trí không làm thay trong danh sách def insertionSort(seq): for i in range(1, len(seq)): key = seq[i] j = i - 1 while j >= 0 and key < seq[j]: seq[j + 1] = seq[j] j -= 1 seq[j + 1] = key
QUICK SORT
The function `def partition(seq, start, stop):` is designed to rearrange elements in a sequence It initializes the pivot index and value, then uses two pointers, `i` and `j`, to traverse the sequence from both ends The algorithm compares the pivot with the elements at these pointers, moving `i` forward when the pivot is less than the current element and moving `j` backward when the pivot is greater If the pointers cross, it swaps the elements at `i` and `j`, continuing this process until the entire sequence is partitioned.
The quicksort algorithm is implemented through a recursive function that sorts a sequence by partitioning it around a pivot element The process begins by checking if the start index is greater than or equal to the stop index, in which case the function returns The partition function rearranges the elements, placing the pivot in its correct position and returning its index The quicksort function then recursively sorts the subarrays to the left and right of the pivot, ensuring an efficient sorting process This method is initiated by calling the quicksort function with the entire sequence.
MERGE SORT
The article discusses the process of merging two sorted sequences in the context of the merge sort algorithm It introduces a function, `merge`, which takes a sequence and indices to combine two halves into a sorted list The function iterates through both halves, comparing elements and appending the smaller one to a new list After processing both halves, any remaining elements are added to the list Finally, the sorted elements are copied back to the original sequence Additionally, the article mentions a recursive function, `mergeSortRecursively`, which is likely used to implement the overall merge sort process.
BÀI 5: 31 if start >= stop - 1: return mid = (start + stop) // 2 mergeSortRecursively(seq, start, mid) mergeSortRecursively(seq, mid, stop) merge(seq, start, mid, stop) def mergeSort(seq): mergeSortRecursively(seq, 0, len(seq))
HEAP SORT
The article discusses the implementation of the heap sort algorithm, which involves two main functions: `heapify` and `heapSort` The `heapify` function is responsible for maintaining the heap property by comparing parent and child nodes, ensuring that the largest element is at the root It recursively adjusts the heap structure when necessary The `heapSort` function first builds a max heap from the input array and then repeatedly extracts the maximum element, placing it at the end of the array while restoring the heap property This efficient sorting algorithm operates in O(n log n) time complexity, making it suitable for large datasets.
RADIX SORT
The article discusses the implementation of the Counting Sort and Radix Sort algorithms in Python The Counting Sort function, `countingSort(arr, exp1)`, initializes an output array and a count array to store the frequency of digits It iterates through the input array to populate the count array, then modifies it to reflect the positions of the digits The sorted elements are placed in the output array, which is then copied back to the original array The Radix Sort function, `radixSort(arr)`, determines the maximum value in the array and repeatedly calls the Counting Sort for each digit, starting from the least significant digit to the most significant This process continues until all digits are processed, resulting in a fully sorted array.
1 main các công sau: a Sinh nhiên n nguyên trong 1 99
BÀI 5: 33 b sinh (câu a) ra màn hình c các pháp và
2 Cho class SinhVien các tính: Ho, Ten, MSSV, DiemTB các các yêu sau: a danh sách n sinh viên (n nhiên) b danh sách sinh viên ra màn hình c danh sách và theo DiemTB các pháp d danh sách và theo MSSV các pháp e danh sách và theo Ten và Ho các pháp
3 Bài nâng cao: a 3 file 100 nguyên file 1 100 nguyên file 2 c 100 nguyên nhiên và file 3 100 nguyên
- thi các pháp trong 3 file theo
- gian thi và ra xét toán b file 1000, 10000, 100000 và 1000000 nguyên xét thi các toán xét best case và worse case
Sau khi xong này sinh viên có
- Cài các toán thao tác
6.1 BI U DI N TH ma danh sách
The `Graph` class is defined to represent a graph using an adjacency matrix It initializes the matrix based on the specified size, creating a two-dimensional list filled with zeros The class includes a method to add edges between vertices, ensuring that self-loops are not allowed Additionally, it provides a method to remove edges, with checks to confirm the existence of an edge before attempting removal.
BÀI 6: - CHU TRÌNH 37 def len (self): return self.size def print_matrix(self): for row in self.adjMatrix: for val in row: print('{:4}'.format(val)), print def main(): g = Graph(5) g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.print_matrix()
The article introduces a class named `Vertex`, which initializes with a node identifier and maintains a dictionary of adjacent vertices It includes methods to add neighbors with associated weights, retrieve connections, obtain the vertex ID, and get the weight of a specific neighbor Additionally, a `Graph` class is defined, which initializes an empty dictionary for vertices and keeps track of the number of vertices in the graph.
In this article, we discuss the implementation of a graph data structure in Python The `add_vertex` method increases the vertex count and creates a new vertex, while the `get_vertex` method retrieves a vertex if it exists in the graph The `add_edge` method connects two vertices, adding them if they are not already present, and establishes a bidirectional relationship between them Finally, the `get_vertices` method returns all the keys of the vertex dictionary, providing a comprehensive view of the graph's vertices.
- 3 có và các ma và danh sách
2 các mã khai báo cho và phát các sau:
- ma danh sách file cho
- In ma danh sách trong file
- ma danh sách sang ma và
- theo sâu (Depth First Search-DFS)
The article discusses two fundamental graph traversal algorithms: Depth First Search (DFS) and Breadth First Search (BFS) The DFS implementation utilizes a stack to explore nodes, starting from a specified vertex, and marks each visited node to avoid repetition Conversely, the BFS algorithm employs a queue to systematically visit nodes level by level, ensuring that all connections from the current node are explored before moving deeper into the graph Both methods effectively traverse graphs, but they differ in their approach and data structure usage.
1 Sinh viên s d ng các th c c giáo trình g i ý, k t h p v i ph n mã ngu n ph n 6.1 vi t trình duy t th theo DFS và BFS hoàn thi n
2 S d ng các th vô ng c t o bài 1 c a ph n 6.1 và th c thi thu t toán v i t ng nh trong th
3 Ki m tra s thành ph n liên thông c a th b ng cách: a Ki m tra s ng nh c in ra b ng th c DFS ho c BFS b ng v i t ng s nh thì th có 1 thành ph n liên thông b N u s nh in ra ít s nh thì th có nhi u 1 thành ph n liên thông c Vi t th c tr v 0 n u nhi u 1 thành ph n liên thông và tr v 1 n u ch có 1 thành ph n liên thông.
BÀI TOÁN CHU TRÌNH
Bài toán: tra có chu trình Euler Ý K tra và
1 (câu 3c) 0 thì không có hay chu trình Euler
2 1, xét và a không có thì có chu trình Euler b có 2 thì có Euler và thúc còn c còn không có chu trình hay Euler.
Ví Mã ma def checkEuler(self): if(self.isConnect()==0): return 3 odd = 0; for row in self.adjMatrix: for element in row:
BÀI 6: - CHU TRÌNH 41 if element > 0: odd+=1 if odd == 0: return 1 elif odd == 2: return 2 elif odd > 2: return 3
Sinh viên hoàn danh sách các vô bài t 1 n 6.1 trong và tra trong tính xác và chu trình
CÂY KHUNG - N NH T
Sau khi xong này sinh viên có
- Cài các toán thao tác có
Khi tìm cây khung, nếu không có giá trị nào, giá trị n sẽ không có 2 Tuy nhiên, khi có giá trị không âm, giá này sẽ được thay thế bằng giá trị âm.
Trong phần 7.1, chúng ta sẽ thảo luận về thuật toán tìm cây khung Ý tưởng chính là sử dụng giá trị boolean để xác định các nút trong cây khung n, trong đó giá trị true biểu thị sự tồn tại của nút, còn giá trị false biểu thị sự không tồn tại Các giá trị của các nút cha trong cây khung sẽ được sử dụng để xây dựng cây khung một cách hiệu quả.
The function `minKey` is designed to find the minimum key value from a set of vertices that have not yet been included in the minimum spanning tree (MST) It initializes a variable `min` to a high value and iterates through all vertices, updating the minimum key and its corresponding index whenever it finds a smaller key value that is not yet part of the MST Finally, it returns the index of the vertex with the minimum key.
BÀI 7: CÂY KHUNG - 43 xây cây khung def primMST(self): key = [999] * self.size parent = [None] * self.size key[0] = 0 mstSet = [False] * self.size parent[0] = -1 for cout in range(self.size):
# u luôn src trong tiên u = self.minKey(key, mstSet)
# cách vào cây khung mstSet[u] = True
The algorithm iterates through the vertices, checking the adjacency matrix for edges with positive weights If a vertex is not included in the minimum spanning tree (MST) and the key value is greater than the edge weight, it updates the key and sets the parent The minimum spanning tree is then printed, displaying the edges and their corresponding weights.
1 Xây d ng các th c xác nh cây khung l n nh t trong th vô ng d a vào mã ngu n c a th c c a thu t toán Prim cho
2 Chuy n th c cho thu t toán tìm cây khung b ng thu t toán Prim cho có th ch y ng v i danh sách k
Máy tính hoạt động liên thông, với một số máy tính kết nối với nhau theo hai chiều Hàng tháng, người dùng phải trả một khoản tiền thuê bao cho các kết nối này Số tiền thuê bao kết nối giữa máy i và máy j (với mối kết nối máy n) sẽ được xác định Sau một thời gian, người dùng nhận thấy có một số kết nối thừa, khi mà mạng vẫn liên thông Thông tin có thể được minh họa qua thuê bao hàng tháng, trong đó các máy được gán chữ cái A, B, ; chữ nào không kết nối với máy thì sẽ trống.
Tìm m t gi i pháp lo i b b t m t s c nh truy n mà v n m b o m ng liên thông sao cho s ti n ph i thuê bao hàng tháng gi m c nhi u nh t Vi t trình th c hi n gi i pháp trên
7.2.1 Tìm ng b ng gi i thu t BFS, DFS toán tìm 2 trong có BFS
BÀI 7: CÂY KHUNG - 45 Ý Thêm tham và cho khi
The Depth-First Search (DFS) algorithm is implemented in the function `DFS(self, start, goal, visited, path)` It begins by marking the starting node as visited and appending it to the path If the starting node matches the goal, the function returns True The algorithm then iterates through the adjacency matrix, checking for unvisited nodes connected to the current node If an unvisited node is found, the DFS function is called recursively If the goal is reached during this process, the function returns True.
#xóa danh sách path(backtrack) path.pop()
The article discusses the implementation of the Breadth-First Search (BFS) algorithm in Python It begins by initializing a list to track visited nodes and a queue to manage the paths to explore The algorithm checks if the starting node is the same as the goal, returning the start if they are equal As the queue processes each path, it retrieves the last node and explores its neighbors using an adjacency matrix For each neighbor that is reachable, a new path is created by appending the neighbor to the current path.
46 BÀI 7: CÂY KHUNG - queue.append(new_path) if i == goal: return new_path visited.append(node)
1 Chu hai BFS và DFS cho thích trên danh sách
Trên một bàn cờ vua kích cỡ vô hạn, có một con mã và một con tốt Vị trí của quân mã là (x, y) và vị trí của quân tốt là (a, b), trong đó x là chỉ số dòng và y là chỉ số cột Quân mã có quyền di chuyển theo 8 hướng xung quanh vua chuẩn Quân tốt chỉ có thể di chuyển một ô về phía trước (từ vị trí (a, b) đến vị trí (a, b+1)) Hai quân cờ sẽ di chuyển theo lượt, xen kẽ nhau Khi một quân cờ vào vị trí của quân cờ khác, quân cờ đó sẽ bị loại khỏi bàn cờ.
Cho c v trí ban u c a hai quân c và t c a quân c Hãy tính quân mã có kh th ng không và n u th ng thì nó s ph i ít nh t là bao nhiêu c
- Dòng ba ghi 0/1 quân quân
- Dòng ghi YES/NO quân có không có
- dòng là YES thì dòng hai ghi ít
7.2.2 Tìm ng b ng gi i thu t Dijkstra Ý
- 1: cách chính nó là #INF, cách ban các nh khác là Ta danh sách các cách các
- 2: a có cách trong danh sách này và ghi
Các sau không xét này
- 3: xét các b nh a u cách b cách ghi thì giá và avào cách a b
- 4: Sau khi xét b a Lúc này ta danh sách cách các Quay 2 danh sách này toán thúc khi cách các def dijkstra(self, start_vertex):
D = {v:float('inf') for v in range(self.size)}
D[start_vertex] = 0 pq = PriorityQueue() pq.put((0, start_vertex)) while not pq.empty():
The algorithm retrieves the current vertex and its distance from the priority queue, marking the vertex as visited It then iterates through all neighboring vertices, checking for valid connections in the adjacency matrix If a neighbor has not been visited, it calculates the new cost by adding the distance to the current vertex's cost If this new cost is lower than the previously recorded cost for that neighbor, it updates the priority queue with the new cost and the neighbor's index.
# for vertex in range(len(D)):
# print("Distance from vertex 0 to vertex", vertex, "is",
1 Dijkstra cho phù danh sách
2 Hùng mua mãi giá cho hành trình
Hà vào TP Chí Minh Hùng có giá trong bay nào Tuy nhiên có giá trong 1 bay duy vào
Dòng tiên bao gồm hai tham số n và m, trong đó n đại diện cho số lượng sân bay trong hành trình và m là số lượng chuyến bay giữa các sân bay Sân bay 1 là sân bay Hà Nội và sân bay 2 là sân bay TP Hồ Chí Minh Mỗi chuyến bay được mô tả bởi ba tham số: sân bay khởi hành, sân bay đến và giá vé Chuyến bay luôn diễn ra giữa Hà Nội và TP Hồ Chí Minh.
In nguyên: giá bay Hà TP Chí Minh
Khi giá cho bay có giá là x, giá nó thành x /