Ebook Data structures and algorithms in C++: Part 2

394 282 0
Ebook Data structures and algorithms in C++: Part 2

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

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

Thông tin tài liệu

Part 2 book “Data structures and algorithms in C++” has contents: Heaps and priority queues, hash tables, maps, and skip lists, search trees, sorting, sets, and selection, strings and dynamic programming, graph algorithms, memory management and B-Trees.

✐ ✐ “main” — 2011/1/13 — 9:10 — page 321 — #343 ✐ ✐ Chapter Heaps and Priority Queues Contents 8.1 8.2 8.3 The Priority Queue Abstract Data Type 8.1.1 Keys, Priorities, and Total Order Relations 8.1.2 Comparators 8.1.3 The Priority Queue ADT 8.1.4 A C++ Priority Queue Interface 8.1.5 Sorting with a Priority Queue 8.1.6 The STL priority queue Class Implementing a Priority Queue with a List 8.2.1 A C++ Priority Queue Implementation using a List 8.2.2 Selection-Sort and Insertion-Sort Heaps 8.3.1 The Heap Data Structure 8.3.2 Complete Binary Trees and Their Representation 8.3.3 Implementing a Priority Queue with a Heap 8.3.4 C++ Implementation 8.3.5 Heap-Sort 8.3.6 Bottom-Up Heap Construction Adaptable Priority Queues 8.4.1 A List-Based Implementation 8.4.2 Location-Aware Entries Exercises ⋆ 8.4 8.5 322 322 324 327 328 329 330 331 333 335 337 337 340 344 349 351 353 357 358 360 361 ✐ ✐ ✐ ✐ ✐ ✐ “main” — 2011/1/13 — 9:10 — page 322 — #344 ✐ ✐ 322 8.1 Chapter Heaps and Priority Queues The Priority Queue Abstract Data Type A priority queue is an abstract data type for storing a collection of prioritized elements that supports arbitrary element insertion but supports removal of elements in order of priority, that is, the element with first priority can be removed at any time This ADT is fundamentally different from the position-based data structures such as stacks, queues, deques, lists, and even trees, we discussed in previous chapters These other data structures store elements at specific positions, which are often positions in a linear arrangement of the elements determined by the insertion and deletion operations performed The priority queue ADT stores elements according to their priorities, and has no external notion of “position.” 8.1.1 Keys, Priorities, and Total Order Relations Applications commonly require comparing and ranking objects according to parameters or properties, called “keys,” that are assigned to each object in a collection Formally, we define a key to be an object that is assigned to an element as a specific attribute for that element and that can be used to identify, rank, or weigh that element Note that the key is assigned to an element, typically by a user or application; hence, a key might represent a property that an element did not originally possess The key an application assigns to an element is not necessarily unique, however, and an application may even change an element’s key if it needs to For example, we can compare companies by earnings or by number of employees; hence, either of these parameters can be used as a key for a company, depending on the information we wish to extract Likewise, we can compare restaurants by a critic’s food quality rating or by average entr´ee price To achieve the most generality then, we allow a key to be of any type that is appropriate for a particular application As in the examples above, the key used for comparisons is often more than a single numerical value, such as price, length, weight, or speed That is, a key can sometimes be a more complex property that cannot be quantified with a single number For example, the priority of standby passengers is usually determined by taking into account a host of different factors, including frequent-flyer status, the fare paid, and check-in time In some applications, the key for an object is data extracted from the object itself (for example, it might be a member variable storing the list price of a book, or the weight of a car) In other applications, the key is not part of the object but is externally generated by the application (for example, the quality rating given to a stock by a financial analyst, or the priority assigned to a standby passenger by a gate agent) ✐ ✐ ✐ ✐ ✐ ✐ “main” — 2011/1/13 — 9:10 — page 323 — #345 ✐ ✐ 8.1 The Priority Queue Abstract Data Type 323 Comparing Keys with Total Orders A priority queue needs a comparison rule that never contradicts itself In order for a comparison rule, which we denote by ≤, to be robust in this way, it must define a total order relation, which is to say that the comparison rule is defined for every pair of keys and it must satisfy the following properties: • Reflexive property : k ≤ k • Antisymmetric property: if k1 ≤ k2 and k2 ≤ k1 , then k1 = k2 • Transitive property: if k1 ≤ k2 and k2 ≤ k3 , then k1 ≤ k3 Any comparison rule, ≤, that satisfies these three properties never leads to a comparison contradiction In fact, such a rule defines a linear ordering relationship among a set of keys If a finite collection of keys has a total order defined for it, then the notion of the smallest key, kmin , is well defined as the key, such that kmin ≤ k, for any other key k in our collection A priority queue is a container of elements, each associated with a key The name “priority queue” comes from the fact that keys determine the “priority” used to pick elements to be removed The fundamental functions of a priority queue P are as follows: insert(e): Insert the element e (with an implicit associated key value) into P min(): Return an element of P with the smallest associated key value, that is, an element whose key is less than or equal to that of every other element in P removeMin(): Remove from P the element min() Note that more than one element can have the same key, which is why we were careful to define removeMin to remove not just any minimum element, but the same element returned by Some people refer to the removeMin function as extractMin There are many applications where operations insert and removeMin play an important role We consider such an application in the example that follows Example 8.1: Suppose a certain flight is fully booked an hour prior to departure Because of the possibility of cancellations, the airline maintains a priority queue of standby passengers hoping to get a seat The priority of each passenger is determined by the fare paid, the frequent-flyer status, and the time when the passenger is inserted into the priority queue When a passenger requests to fly standby, the associated passenger object is inserted into the priority queue with an insert operation Shortly before the flight departure, if seats become available (for example, due to last-minute cancellations), the airline repeatedly removes a standby passenger with first priority from the priority queue, using a combination of and removeMin operations, and lets this person board ✐ ✐ ✐ ✐ ✐ ✐ “main” — 2011/1/13 — 9:10 — page 324 — #346 ✐ ✐ Chapter Heaps and Priority Queues 324 8.1.2 Comparators An important issue in the priority queue ADT that we have so far left undefined is how to specify the total order relation for comparing the keys associated with each element There are a number of ways of doing this, each having its particular advantages and disadvantages The most direct solution is to implement a different priority queue based on the element type and the manner of comparing elements While this approach is arguably simple, it is certainly not very general, since it would require that we make many copies of essentially the same code Maintaining multiple copies of the nearly equivalent code is messy and error prone A better approach would be to design the priority queue as a templated class, where the element type is specified by an abstract template argument, say E We assume that each concrete class that could serve as an element of our priority queue provides a means for comparing two objects of type E This could be done in many ways Perhaps we require that each object of type E provides a function called comp that compares two objects of type E and determines which is larger Perhaps we require that the programmer defines a function that overloads the C++ comparison operator “

Ngày đăng: 20/01/2020, 23:07

Từ khóa liên quan

Mục lục

  • Cover

  • Title Page

  • Copyright

  • Preface

  • Contents

  • 1 A C++ Primer

    • 1.1 Basic C++ Programming Elements

      • 1.1.1 A Simple C++ Program

      • 1.1.2 Fundamental Types

      • 1.1.3 Pointers, Arrays, and Structures

      • 1.1.4 Named Constants, Scope, and Namespaces

      • 1.2 Expressions

        • 1.2.1 Changing Types through Casting

        • 1.3 Control Flow

        • 1.4 Functions

          • 1.4.1 Argument Passing

          • 1.4.2 Overloading and Inlining

          • 1.5 Classes

            • 1.5.1 Class Structure

            • 1.5.2 Constructors and Destructors

            • 1.5.3 Classes and Memory Allocation

            • 1.5.4 Class Friends and Class Members

            • 1.5.5 The Standard Template Library

            • 1.6 C++ Program and File Organization

              • 1.6.1 An Example Program

              • 1.7 Writing a C++ Program

                • 1.7.1 Design

Tài liệu cùng người dùng

Tài liệu liên quan