Public Class TreeListPrivate count As Integer = 0 Private first As Node Public Sub addLetterByVal Letter As String Dim hTemp As New HuffmanTreeLetter Dim eTemp As New NodehTemp If first
Trang 1Public Class TreeList
Private count As Integer = 0 Private first As Node
Public Sub addLetter(ByVal Letter As String) Dim hTemp As New HuffmanTree(Letter)
Dim eTemp As New Node(hTemp)
If (first Is Nothing) Then first = eTemp
Else eTemp.link = first first = eTemp End If
count += 1 End Sub
Public Sub sortTree() Dim otherList As New TreeList Dim aTemp As HuffmanTree While Not (Me.first Is Nothing) aTemp = Me.removeTree()
otherList.insertTree(aTemp) End While
Me.first = otherList.first End Sub
Public Sub mergeTree()
If Not (first Is Nothing) Then
If Not (first.link Is Nothing) Then Dim aTemp As HuffmanTree = removeTree() Dim bTemp As HuffmanTree = removeTree() Dim sumTemp As New HuffmanTree
sumTemp.setLeftChild(aTemp) sumTemp.setRightChild(bTemp) sumTemp.setFreq(aTemp.getFreq + bTemp.getFreq)
Trang 2P1: JtR
insertTree(sumTemp) End If
End If End Sub
Public Function removeTree() As HuffmanTree
If Not (first Is Nothing) Then Dim hTemp As HuffmanTree hTemp = first.data
first = first.link count -= 1
Return hTemp End If
Return Nothing End Function
Public Sub insertTree(ByVal hTemp As HuffmanTree) Dim eTemp As New Node(hTemp)
If (first Is Nothing) Then first = eTemp
Else Dim p As Node = first While Not (p.link Is Nothing)
If (p.data.getFreq <= hTemp.getFreq And _ p.link.data.getFreq >= hTemp.getFreq) Then Exit While
End If
p = p.link End While eTemp.link = p.link p.link = eTemp End If
count += 1 End Sub
Public Function length() As Integer Return count
End Function
End Class
Trang 3P1: JtR
This class makes use of the HuffmanTree class, so let’s view that code now:
Public Class HuffmanTree
Private leftChild As HuffmanTree Private rightChild As HuffmanTree Private Letter As String
Private freq As Integer
Public Sub New(ByVal Letter As String) Me.Letter = Letter
End Function
Public Function getLetter() As String Return Letter
Trang 4P1: JtR
End Function Public Function getFreq() As Integer Return freq
Dim treeList As New TreeList Dim i As Integer
For i = 0 To input.Length - 1 treeList.addSign(input.Chars(i)) Next
treeList.sortTree() ReDim signTable(input.Length) ReDim keyTable(input.Length) While (treeList.length > 1) treeList.mergeTree() End While
makeKey(treeList.removeTree, "") Dim newStr As String = translate(input) For i = 0 To signTable.Length - 1
Console.WriteLine(signTable(i) & " : " & _
keyTable(i)) Next
Console.WriteLine("The original string is " & _
input.Length * 16 & " bits long") Console.WriteLine("The new string is " & _
newStr.Length & " bits long.") Console.WriteLine _
("The coded string looks like this: " & newStr) Console.Read()
End Sub
Trang 5If (original.Chars(i) = signTable(j)) Then newStr &= keyTable(j)
End If Next Next Return newStr End Function
Sub makeKey(ByVal tree As HuffmanTree, ByVal code _
As String)
If (tree.getLeftChild Is Nothing) Then signTable(pos) = tree.getSign() keyTable(pos) = code
pos += 1 Else
makeKey(tree.getLeftChild, code & "0") makeKey(tree.getRightChild, code & "1") End If
End Sub
A Greedy Solution to the Knapsack Problem
Earlier in this chapter we examined the knapsack problem and wrote a gram to solve the problem using dynamic programming techniques In thissection we look at the problem again, this time looking for a greedy algorithm
pro-to solve the problem
To use a greedy algorithm to solve the knapsack problem, the items we areplacing in the knapsack need to be “continuous” in nature In other words,they must be items like cloth or gold dust that cannot be counted discretely If
we are using these types of items, then we can simply divide the unit price bythe unit volume to determine the value of the item An optimal solution is toplace as much of the item with the highest value in the knapsack as possibleuntil the item is depleted or the knapsack is full, followed by as much of thesecond highest value item as possible, and so on The reason we can’t find
Trang 6P1: JtR
an optimal greedy solution using discrete items is that we can’t put “half a
television” into a knapsack
Let’s look at an example You are a carpet thief and you have a knapsack thatwill store only 25 “units” of carpeting Therefore, you want to get as much of
the “good stuff” as you can to maximize your take You know that the carpet
store you’re going to rob has the following carpet styles and quantities on
hand (with unit prices):
Being the computational type, you first write a program to model your heist
Here is the code you come up with:
Option Strict On Module Module1 Public Class Carpet Implements IComparable Private item As String Private val As Single Private unit As Integer
Public Sub New(ByVal i As String, ByVal v As _
Single, ByVal u As Integer) item = i
val = v unit = u End Sub Public Function CompareTo(ByVal obj As Object) As _ Integer Implements System.IComparable.CompareTo Return Me.val.CompareTo(CType(obj, Carpet).val) End Function
Public ReadOnly Property getUnit() As Integer Get
Return unit
Trang 7P1: JtR
End Get End Property
Public ReadOnly Property getItem() As String Get
Return item End Get
Public Class Knapsack Private quantity As Single Dim items As New SortedList Dim itemList As String
Public Sub New(ByVal max As Single) quantity = max
If (tempTot <= quantity) Then totalUnits += CType(objects(pos), _
Carpet).getUnit totalVal += CType(objects(pos), Carpet).getVal
Trang 8itemVal * tempUnit totalVal += tempVal
totalUnits += CInt(tempUnit) items.Add(CType(objects(pos), Carpet) _
getItem, tempUnit) End If
pos -= 1 End While End Sub
Public Function getItems() As String Dim k, v As Object
For Each k In items.GetKeyList itemList &= CStr(k) & ": " & _
CStr(items.Item(k)) & " "
Next Return itemList End Function End Class
Sub Main() Dim c1 As New Carpet("Frieze", 1.75, 12) Dim c2 As New Carpet("Saxony", 1.82, 9) Dim c3 As New Carpet("Shag", 1.5, 13) Dim c4 As New Carpet("Loop", 1.77, 10) Dim rugs As New ArrayList
rugs.Add(c1) rugs.Add(c2) rugs.Add(c3) rugs.Add(c4) rugs.Sort() Dim k As New Knapsack(25)
Trang 9P1: JtR
k.FillSack(rugs) Console.WriteLine(k.getItems) Console.Read()
End Sub End Module
The Carpet class is used for two reasons—to encapsulate the data abouteach type of carpeting and to implement the IComparable interface, so wecan sort the carpet types by their unit cost
The Knapsack class does most of the work in this implementation It vides a list to store the carpet types and it provides a method, FillSack, todetermine how the knapsack gets filled Also, the constructor method allowsthe user to pass in a quantity that sets the maximum number of units theknapsack can hold
pro-The FillSack method loops through the carpet types, adding as much ofthe most valuable carpeting as possible into the knapsack, then moving on tothe next type At the point where the knapsack becomes full, the code in theElse clause of the If statement puts the proper amount of carpeting into theknapsack
This code works because we can cut the carpeting wherever we want If
we were trying to fill the knapsack with some other item that does not come
in continuous quantities, we would have to move to a dynamic programmingsolution
This chapter examined two advanced techniques for algorithm design: namic programs and greedy algorithms Dynamic programming is a techniquewhere a bottom-up approach is taken to solving a problem Rather than work-ing its way down to the bottom of a calculation, such as done with recursivealgorithm, a dynamic programming algorithm starts at the bottom and builds
dy-on those results until the final solutidy-on is reached
Greedy algorithms look for solutions as quickly as possible and then stopbefore looking for all possible solutions A problem solved with a greedyalgorithm will not necessarily be the optimal solution because the greedyalgorithm will have stopped with a “sufficient” solution before finding theoptimal solution
Trang 10P1: JtR
EXERCISES
1. Rewrite the longest common substring code as a class
2. Write a program that uses a brute-force technique to find the longest
com-mon substring Use the Timing class to compare the brute-force methodwith the dynamic programming method Use the program from Exercise 1for your dynamic programming solution
3. Write a Windows application that allows the user to explore the knapsack
problem The user should be able to change the capacity of the knapsack,the sizes of the items, and the values of the items The user should alsocreate a list of item names that is associated with the items used in theprogram
4. Find at least two new coin denominations that make the greedy algorithm
for coin changing shown in the chapter produce suboptimal results
5. Using a “commercial” compression program, such as WinZip, compress
a small text file Then compress the same text file using a Huffman codeprogram Compare the results of the two compression techniques
6. Using the code from the “carpet thief” example, change the items
be-ing stolen to televisions Can you fill up the knapsack completely? Makechanges to the example program to answer the question
Trang 11P1: JtR
378
Trang 12Cormen, Thomas H., Leiserson, Charles E., Rivest, Ronald L., and Clifford
Stein Introduction to Algorithms Cambridge, Massachusetts: The MIT Press,
2001
Ford, William and William Topp Data Structures with C++ Upper Saddle
River, New Jersey: Prentice Hall, 1996
Friedel, Jeffrey E F Mastering Regular Expressions Sebastopol, California:
O’Reilly and Associates, 1997
Knuth, Donald E., The Art of Computer Programming, Volume 1, Fundamental
Algorithms Reading, Massachusetts: Addison Wesley, 1998.
LaFore, Robert Data Structures and Algorithms in Java Corte Madera,
California: Waite Group Press, 1998
McMillan, Michael Object-Oriented Programming with Visual Basic.NET New
York: Cambridge University Press, 2004
Sedgewick, Robert Algorithms in C Reading, Massachusetts: Addison Wesley,
1998
Weiss, Mark Allen Data Structures and Algorithm Analysis in Java Reading,
Massachusetts: Addison Wesley, 1999
379
Trang 13P1: IWV
380
Trang 14P1: KaD
0521547652ind CB820-McMillan-v1-ind April 21, 2005 21:38
Index
Symbols and Numbers
# wildcard, used in Like
$ (dollar sign), assertion
& (ampersand) operator,
using for stringconcatenation 167
{} (curly braces), surrounding
the members of a set 268
+ (plus sign) quantifier 185
<< (left shift operator) 133–134
>> (right shift operator) 133–134
(period) character class 187–188
? (question mark)quantifier 186,187
wildcard in Like
() parentheses, surroundingregular expressions 191
in a BucketHash class 215
of the CollectionBase class 27
for a dictionary object 201–202
of the Hashtable class 219
storing data in a collection 23
for a strongly typed
Trang 15arrays 15,26,46
building heaps 288
compared to ArrayLists 65–70
compared to BitArrays 148
compared to linked lists 228
copying the contents of
declaring 47,48
deleting elements from 15
designing hash tablestructures around 210
doubling the number of
storing linear collections 15
transferring the contents
Trang 16benchmarking See timing tests
binary number system 126–128
binary search algorithm 93,96–97
binary search trees 21,252
building 252–254
finding node andminimum/maximumvalues in 257–259
handling unbalanced 298
inserting a series ofnumbers into 255
removing leaf nodes 259–261
bit mask, 137 See alsomask
bit pattern for an integer value 134
Trang 17Boolean truth tables 128
Boolean values, computingthe union of two sets 278
brackets ([]), enclosing acharacter class 189
of the ArrayList class 59
placing before a character
character array, instantiating a
character classes 187–190
charactersadding to the end of aStringBuilder object 172
compressing a string of 366
defining a range of 188
matching any in a string 187
removing from aStringBuilder object 175
removing from either end
Trang 18of the CStack class 101
for a dictionary object 201
of the Hashtable class 222
of the Stack class 107
properties and methods
looping through elements in 32
retrieving items from aspecified position 43
returning the index of theposition of an item in 29
sub-categories of 15–21
collisions 211,215–218
comma-delimited strings 156
comma-separated valuestrings (CSVs) 156
commutative set property 269
the CSet class 270
the CStack class 101
the Node class 230
the Stack class 103
for ArrayLists 60
for BitArrays 140
Trang 19for an enumerator class 31
for strongly typed
of the ArrayList class 59
of the CollectionBase class 27
of the CStack class 101
of the Hashtable class 222
retrieving collection items 24
compressing 365–372
searching in a hash table 214
sorting with queues 116–119
for a Timing class 10
data structures, initializing
data typesdetermining for arrays 51
Trang 20distributive set property 269
dollar sign ($), assertion
adding to an array 15
inserting into a full array 67
setting and accessing array 49
Trang 21P1: KaD
equalities for sets 270
equality, testing for 4
Equals method of theCollectionBase class 41
fields Seedata members
FIFO (First-In, First-Out)structures 19,110
For Each statement 25,32
garbage collector, calling 8
Trang 22resetting the iterator to 241
header of a linked list 228
removing nodes from 291
running all function
IComparable interface 299
IDictionary interface 201
IEnumerable interface 30
IEnumerator interface 30
Trang 23P1: KaD
If-Then statement,short-circuiting 92
IgnoreCase option for aregular expression 197
IgnorePatternWhiteSpaceoption for a regular
of the ArrayList class 60,61
of the AVLTree class 301
of the BinarySearchTree
of the CollectionBase
for a doubly-linked list 234
inserting a node into a heap 290
of the LinkedList class 231
of the SkipList class 315
of the String class 163
into a red-black tree 304
determining the bit pattern
Trang 24IP addresses, class storing 201
isArray class method 51
IsFull Private function 27
Item method
of the ArrayList class 60
for a dictionary object 201–202
of the Hashtable class 219,220
implementing as a Property
retrieving collection items 24
retrieving values from aSortedList object 207
items, retrieving from a
in a hash table 20,210
retrieving collection items 24
retrieving hash table
Llabel data member of theVertex class 322
left nodes of a binary
Trang 25P1: KaD
levelsbreaking a tree down into 251
determining for skip lists 312
inserting items into 229
marking the beginning
modifying 233–239
object-orienteddesign of 229–233
printing in reverse order 235
referring to two or morepositions in 239
removing items from 229
removing nodes from 241
traversing backwards 233
LinkedListclass 230,236–239,241–242
linksadding to skip lists 312
searching an array for 90
membersremoving from a set 271
merge method, called byrecMergeSort 287–288
MergeSort algorithm 285–288
Trang 26implementing topologicalsorting 327–330
performing operations ondata in a structure 16
midpoint in a binary search 93
minimum spanning trees 336–339
minimum value
in a binary search tree 257
searching an array for 89
native data type 151
negation of a character class 190
negative integers, binary
representation of 135
negative lookahead assertion 195
negative lookbehind assertion 195
.NET environment, timingtests for 7–10
for a binary search tree 252
building heap data from 289
compared to the Vertex
for Huffman coding 366
modifying for adoubly-linked list 233
nodesallocating to link levels
connected by edges 249
creating the linkage for 230
deleting from adoubly-linked list 235
determining the properposition for 253
inserting into a skip list 315
inserting into linked lists 231
inserting into the heap
in linked lists 228
Node class data members of 229
removing from BSTs 259–266
removing from heaps 291
removing from linked lists 232
returning the height of 299
shifting in a heap 290
of a tree collection 20