
本书是算法设计畅销书的最新版本,是设计实用且高效算法的最全面指导书。本书揭密了算法的设计与分析,以简单易懂的写作风格,介绍了各种算法技术,着重强调了算法分析,全书包括两大部分,“技术”部分介绍了设计和分析计算机算法的各种方法,“资源”部分给出了大量的参考资源,以及算法实现的各种资源,此外,在作者的个人网址http://www.cs.sunysb.edu/~algorith/上还提供了各种教学资源和参考材料,这些资源对读者很有参考价值。
本书可以作为算法设计课程的主教材,也是程序人员、研究人员和学生的常备参考书。
Most professional programmers that I've encountered are not well prepared to
''
tackle algorithm design problems. This is a pity, because the techniques of algorithm
design form one of the core practical technologies of computer science. Designing
correct, efficient, and implementable algorithms for real-world problems requires
access to two distinct bodies of knowledge:
. Techniques -- Good algorithm designers understand several fundamental
algorithm design techniques, including data structures, dynamic programming,
depth-first search, backtracking, and heuristics. Perhaps the single most
important design technique is modeling, the art of abstracting a messy real--world
application into a clean problem suitable for algorithmic attack.
. Resources -- Good algorithm designers stand on the shoulders of giants.
Rather than laboring from scratch to produce a new algorithm for every task,
they can figure out what is known about a particular problem. Rather than
y can figure out what is known about a particular problem. Rather than
. 1
re-implementing popular algorithms from scratch, they seek existing
impleI
mentations to serve as a starting point. They are familiar with many classic
algorithmic problems, which provide sufficient source material to model most
1.
any application.
This book is intended as a manual on algorithm design, providing access to
combinatorial algorithm technology for both students and computer professionals.
It is divided into two parts: Techniques and Resources. The former is a general
guide to techniques for the design and analysis of computer algorithms. The
Resources section is intended for browsing and reference, and comprises the catalog
of algorithmic resources, implementations, and an extensive bibliography.
. o n
yi P REFA C E
To the Reader
I have been gratified by the warm reception the first edition of The Algorithm
De.
sign Manual has received since its initial publication in 1997. It has been recognized
an Manual has received since its initial publication in 1997. It has been recognized
.. 1
as a unique guide to using algorithmic techniques to solve problems that often arise
'
.'. ri..
in practice. But much has changed in the world since the The Algorithm Design
Manual was first published over ten years ago. Indeed, if we date the origins of
1 1.,-1 1. 1 1.
modern algorithm design and analysis to about 1970, then roughly 30% of modern
algorithmic history has happened since the first coming of The Algorithm Design
Manual.
aam
J'hree aspects of The Alqorlthm Deslqn Manual have been particularly beloved:
poets of The Algorithm Design Manual have been particularly beloved:
(1) the catalog of algorithmic problems, (2) the war stories, and (3) the electronic
component of the book. These features have been preserved and strengthened in
this edition:
. The Cataloa o[Alaorithmic Problems -- Since finding out what is known about
u Of Algorithmic Pro6lems -- Since finding out what is known about
1..
an algorithmic problem can be a difficult task, I provide a catalog of the
~ C
75 most important problems arising in practice. By browsing through this
.
catalog, the student or practitioner can quickly identify what their problem is
11 1 1,. 1 1 I., 1 1
called, what is known about it, and how they should proceed to solve it. To aid
. 1 1. 1,. ac
in problem identification, we include a pair of "before" and "after" pictures for
problem identification, we include a pair of "before" and "after" pictures for
1 1 1. 11 1 1.
each problem, illustrating the required input and output specifications. One
problem, illustrating the required input and output specifications. One
perceptive reviewer called my book "The Hitchhiker's Guide to Algorithms"
on the strength of this catalog.
ac
1'he catalog is the most important part of this book. To update the catalog
for this edition, I have solicited feedback from the world's leading experts on
each associated problem. Particular attention has been paid to updating the
discussion of available software implementations for each problem.
TT r 9'. r,. 1..
. War Stories -- In practice, algorithm problems do not arise at the beginning of
a large project. Rather, they typically arise as subproblems when it becomes
1,-1
clear that the programmer does not know how to proceed or that the current
1
solution is inadequate'
m. I h
fo provide a better perspective on how algorithm problems arise in the real
1 1. 1 1 11
world, we include a collection of "war stories," or tales from our experience
. I
with real problems. The moral of these stories is that algorithm design and
1..
analysis is not just theory, but an important tool to be pulled out and used
J Just theory, but an important tool to be pulled out and used
1 1
as needed.
acid lition retains all the oriqiviol lying FI
1'his edition retains all the original war stories (with updates as appropriate)
1 1 1. I. 1
plus additional new war stories covering external sorting, graph algorithms,
. 1 1 1 1. 1 LI,.
simulated annealing, and other topics'
. Electronic Component -- Since the Dractical Derson is usually looking for a
ponent -- Since the practical person is usually looking for a
.
program more than an algorithm, we provide pointers to solid
implementations whenever they are available. We have collected these implementations
P REF A C E vii
.
at one central website site (http://www. cs.sunysb. edwhalgorith) for easy
retrieval. We have been the number one "Algorithm" site on Google pretty
much since the initial publication of the book.
Further, we provide recommendations to make it easier to identify the correct
code for the lob. With these imDlementations available. the critical issue
JOb. With these implementations available, the critical issue
. 1.,-1 1. 1 1 1 1. 1.
in algorithm design becomes properly modeling your application, more so
than becoming intimate with the details of the actual algorithm. This focus
permeates the entire book.
Equally important is what we do not do in this book. We do not stress the
mathematical analysis of algorithms, leaving most of the analysis as informal
arysis of algorithms, leaving most of the analysis as informal
arguments. You will not find a single theorem anywhere in this book. When more
details are needed, the reader should study the cited programs or references. The
goal of this manual is to get you going in the right direction as quickly as possible.
TO the instructor
This book covers enough material for a standard introduction to Algorithms course.
We assume the reader has completed the equivalent of a second programming
course, typically titled Data Structures or Computer Science 11.
A full set of lecture slides for teaching this course is available online at
http://www' algorist.com. Further, I make available online audio and video lectures
..
using these slides to teach a full-semester algorithm course. Let me help teach your
1,-1. P t-1 r
course, by the magic of the internet!
This book stresses design over analysis. It is suitable for both traditional lecture
courses and the new "active learning" method, where the professor does not lecture
but instead guides student groups to solve real problems. The "war stories" provide
.
an appropriate introduction to the active learning method.
.
I have made several pedagogical improvements throughout the book.
Textbookoriented features include:
. More Leisureltl Discussion -- The tutorial material in the first Dart of the book
y Discussion -- The tutorial material in the first part of the book
has been doubled over the previous edition. The pages have been devoted to
more thorough and careful exposition of fundamental material, instead of
adding more specialized topics.
. False Starts -- Algorithms textbooks generally present important algorithms
as a fait accompli, obscuring the ideas involved in designing them and the
subtle reasons whV other approaches fail. The war stories illustrate such
den pproaches fail. The war stories illustrate such
development on certain applied problems, but I have expanded such coverage
.
into classical algorithm design material as well.
. Stop and Think -- Here I illustrate my thought process as I solve a
topicspecific homework problem--false starts and all. I have interspersed such
... o n.
vill P RE F A C E
1 1 1 1 1,-1 1, I-1 1
problem blocks throughout the text to increase the problem-solving activity
of my readers. Answers appear immediately following each problem.
. More and Improved HOmework Problems -- This edition of The Alqorithm
proved HOmework Problems -- This edition of The Algorithm
Design Manual has twice as many homework exercises as the previous one.
Exercises that proved confusing or ambiguous have been improved or
re1 1 n
placed. Degree of difficulty ratings (from 1 to 10) have been assigned to all
1 1
problems.
. Sell-Motlvatlna Exam Design -- In my algorithms courses, I promise the
stuJ,ffotivating Exam Design -- In my algorithms courses, I promise the
students that all midterm and final exam questions will be taken directly from
homework problems in this book. This provides a "student-motivated exam,"
.
so students know exactly how to study to do well on the exam. I have carefully
. 1 1 I- 1,. l., 1 1. m 1
picked the quantity, variety, and difficulty of homework exercises to make this
1..
work; ensuring there are neither too few or too many candidate problems.
. Take-Home Lessons -- Highlighted "take-home" lesson boxes scattered
.
throughout the text emphasize the big--picture concepts to be gained from
the chapter.
. Links to Proqrammina Challenae Pro6lems -- Each chaDter's exercises will
.iapping Challenge Problems -- Each chapter's exercises will
contain links to 3-5 relevant "Programming Challenge" problems from
P REF A C E ix
taught courses using a manuscript version of this edition. Thanks also to my
Springer-Verlag editors, Wayne Wheeler and Allan Wylde.
A select group of algorithmic sages reviewed sections of the Hitchhiker's guide,
sharing their wisdom and alerting me to new developments. Thanks to:
Ami Amir, Herve Bronnimann, Bernard Chazelle, Chris Chu, Scott
Cotton, Yefim Dinitz, Komei Fukuda, Michael Goodrich, Lenny Heath,
Cihat Imamoglu, Tao Jiang, David Karger, Giuseppe Liotta, Albert
Mao, Silvano Martello, Catherine McGeoch, Kurt Mehlhorn, Scott
A. Mitchell, Naceur Meskini, Gene Myers, Gonzalo Navarro, Stephen
North, Joe O'Rourke, Mike Paterson, Theo Paviidis, Seth Pettie, Michel
Pocchiola, Bart Preneel, Tomasz Radzik, Edward Reingold, blank
Ruskey, Peter Sanders, Joao Setubal, Jonathan Shewchuk, Robert
Skeel, Jens Stoye, Torsten Suel, Bruce Watson, and Uri Zwick.
Several exercises were originated by colleagues or inspired by other texts.
Reconstructing the original sources years later can be challenging, but credits for each
problem (to the best of my recollection) appear on the website.
It would be rude not to thank important contributors to the original edition.
Ricky Bradley and Dario Vlah built up the substantial infrastructure required for
the WWW site in a logical and extensible manner. Zhong Li drew most of the
catalog figures using xfig' Richard Crandall, Ron Danielson, Takis Metaxas, Dave
Miller, Gin Narasimhan, and Joe Zachary all reviewed preliminary versions of the
first edition; their thoughtful feedback helped to shape what you see here.
Much of what I know about algorithms I learned along with my graduate
students. Several of them (YaW-Ling Lin, Sundaram Gopalakrishnan, Ting Chen,
Mancine Evans, Harald Ran, Ricky Bradley, and Dimitris Margaritis) are the real
heroes of the war stories related within. My Stony Brook friends and algorithm
colleagues Estie Arkin, Michael Bender, Jie Gao, and Joe Mitchell have always
been a pleasure to work and be with. Finally, thanks to Michael Brochstein and
the rest of the city contingent for revealing a proper life well beyond Stony Brook.
d o a a proper life well beyond Stony Brook.
Caveat
It is traditional for the author to magnanimously accept the blame for whatever
deficiencies remain. I don't. Any errors, deficiencies, or problems in this book are
somebody else's fault, but I would appreciate knowing about them so as to
deters
. 1.
mine who is to blame.
Q+nven S' Skiena
steven S' Skiena
Department of Computer Science
q+nnxr "rook Universitlr
otony Brook University
J Brook University
q+ ac v NY 11794-4400
otonv Brook. NY 11794-4400
U
11roductiontoAlgorithmDesign 3
1. IRob ot hur Opt imiz at ion…………………. 5
1.ZSelectingtheRigMJobs…………………..9
1.3ReasoningaboutCorrectness………………..11
1. 4 Modeling the Problem…………………… 19
1.SAbouttherstories……………………22
1.6rstOYy:PSyChiCMOd6lillg………………..23
1. 7 Exercises………………………….. 2 7
2 Algorithm Analysis 31
2.ITheRAMModelofComputation………………31
2.ZTheBigohNotation…………………….34
2.3 GrowthRates and DomlnanceRelatlons………….. 37
2.4 Working with the Big Oh…………………. 40
2.SReasoningAboutEfficiency…………………41
2.6 Logarithms and TheirApplications…………….. 46
2.7 ProPerties ofLogarithms………………….. 50
2.8rstory:MysteryofthePyramids…………….51
2. 9 Ad、nced Analysis(”)…………………… 54
2. 10 Exercises………………………….. 5 7
3Datastructures 65
3.IContlguous vs. Llnhd Data Structures…………… 66
xii C O N T E N T S
3.2 Stacks and Queues…………………….. 71
3.3Dictionaries…………………………72
3.4Blnarysearchlees……………………..77
3.SPriorityQueues……………………….83
3.6rstory:Strippingliangulations…………….85
3.7Hashingandstrings…………………….89
3.SSpecializedDatastructures…………………93
3. 9r Story: String’ e: Up…………………. 94
3.10 Exercises………………………….. 98
4Sortingandsearching 103
4.IAPPlications ofsorting…………………… 104
4.2 Pragmatics ofsorting……………………. 107
4.3H6&PSOFt:kstSOftlllgV18D8t8StfllCtllY6S…………108
4.4Vr Story: GIVe me aTickt on allAirPlalle……….. 118
4.SM6fg6SOft:SOftlllgbyDIVld6-llld-COllqll6ll…………120
4.6Qulcksort:SortingbyRandomization……………123
4.7DIStyiblltiollSOYt:SOYtillgVi8BllChtillg…………..129
4.8rstory:SkienafortheDefense……………..131
4.9BlnarySearchandRelatedAlgorithms……………132
4.10 Divide-and-Conquer……………………..135
4. 11 Exercises………………………….. 139
SGraphThaversal 145
5.IFlavorsofGraphs………………………146
5.ZDatastructuresforGraphs…………………151
5. 3r Stofy: IWSS 8 VICtith Of MOOW6’ S L8iYV………… 155
5. 4r Story: Getting the G:anh……………….. 158
5.slaversingaGraph……………………..161
5.6Breadth-Firstsearch…………………….162
5.7 Applications ofBreadth-First Search……………. 166
5.SDepth-Firstsearch……………………..169
5.9 Applications ofDepth-First Search…………….. 172
5.10 Depth-First Search on Directed Graphs…………..178
5. 11 EXer………………………….. 184
6 Weighted Graph Algorithmslgl
6.IMlnlmumSPanninglees………………….192
6.2 WaY Story: NOthillg but NetS……………….. 202
6.3 Shortest Paths………………………..205
6.4War S t cry:Dialing for Documes……………..212
6.5 NetworkFlows andBipartiteMatching………….. 217
6.6DeslgnGraPhs,NotAlgorithms……………….222
6. 7 Exercises………………………….. 2 2 5
C O N T E N T S xiii
7. IB ackt r aching………………………… 2 31
7. 2 Search Pruning………………………. 238
7.3 Sud。ku…………………………… 239
7.4rstory:CoveringChessboards………………244
7.SHeuristicsearchMethods………………….247
7. 6Waf Stofy: Oilly it is NOt fi R3diO…………….. 260
7.7rstory:AnnealingArrs………………..263
7.SOtherHeuristicsearchMethods………………266
7.9 Parallelorithms…………………….. 267
7. 10r Story: Going Nowhere kst………………. 268
7.11 Exercises…………………………..270
SDgnamlcProgramming 273
8.ICachingvs.Computation………………….274
8.ZAPProxlmatestringMatching………………..280
8.3Lngestlncreasingsequence…………………289
8.4rstory:EvolutionoftheLobster…………….291
8.SThePartitionProblem……………………294
8.6ParsingCoext一eeGrammars………………298
8.7 Llmltatlons ofDynamic Programming: TSP………… 301
8. 8r Stofy: Whst’ S PSSt is Pfolog……………… 304
8. 9r Story: IXt Compression for Bar Codes……….. 307
8.10 Exercises………………………….. 310
9.IProblems and Reductions…………………. 317
9.ZReductionsforAlgorithms………………….319
9.3ElementaryHardnessReductions………………323
9.4 Satisfiability………………………… 328
9.SCreatlVeReductiolls…………………….330
9.6TheArtofProvingHardness………………..334
9. 7r Story: Hard Against t he C Ic Ck…………….. 3 3 7
9. 8 War Sy: And Thenl Failed……………….. 339
9.9 P.…………………………..
9.10 Dealing with NP-complete Problems…………….344
9.11 Exercises………………………….. 350
10 How to Design Algorithms 356
11 The Hitchhiker’s Guide to Algorithms 361
11A Catalog of Algorithmic Problems 363
.
xlv C O N T E N T S
12 Data Structures 366
1 2. ID i c t i o n a r i e s..............................3 6 7
1 2. ZP r i o r i t yQ u e u e s......'.....................3 7 3
12'3 Suffix Trees and Arrays........................ 377
12'4 Graph Data
C O N T E N T S xv
1 5. 1 ID r ac i n gTr e e s.............................5 1 7
15'12 Planaritv Detection and Embedding 520
J Detection and Embedding................ 520
16 Graph Problems: Hard Problems 523
1 6. IC I i q u e............................... 2 5
1 6. ZI n d e p e n d e n iS e t............................5 2 8
1 6. 3Ve r t e xC o v e r..............................5 3 0
16.4 Trailling Salesman Problem..................... 533
1 6. SH a m i I t o n i a nC y c 1 e..........................5 3 8
1 6. 6G r a p hp a r t i t i o n............................5 4 1
1 6. 7Ve r t e xC o I o r i n g............................5 4 4
1 6. SE d g eC o I o r i n g.............................5 4 8
16'9 Graph
.
xvi C O N T E N T S
19 Algorithmic Resources 657
1 9. IS o fi w a r eS y s t e m s...........................6 5 7
l 9. ZD a t aS o u r c e s..............................6 6 3
19'3 Online Bibliographic Resources................... 663
19.4 Professional Consulting Services................... 664
Bibliography 665
Index 709