640 likes | 731 Views
Chapter 9. Priority Queues, Heaps, and Graphs. Goals. Describe a priority queue at the logical level and implement a priority queue as a list Describe the shape and order property of a heap and implement a heap in a nonlinked tree representation in an array
E N D
Chapter 9 Priority Queues, Heaps, and Graphs
Goals • Describe a priority queue at the logical level and implement a priority queue as a list • Describe the shape and order property of a heap and implement a heap in a nonlinked tree representation in an array • Implement a priority queue as a heap • Compare the implementations of a priority queue using a heap, a linked list, and a binary search tree
Goals • Define the following terms related to graphs: • Directed graph Complete graph • Undirected graph Weighted graph • Vertex Adjacency matrix • Edge Adjacency list • Path • Implement a graph using an adjacency matrix to represent the edges
Goals • Explain the difference between a depth-first and a breadth-first search and implement these searching strategies using stacks and queues for auxiliary storage • Implement a shortest-path operation, using a priority queue to access the edge with the minimum weight • Describe a set at the logical level and implement a set both explicitly and implicitly
Priority Queue Priority Queue An ADT in which only the item with the highest priority can be accessed
Priority Queue Items on a priority queue are made up of <data, priority> pairs Can you think of how a priority queue might be implemented as An unsorted list? An array-based sorted list? A linked sorted list? A binary search tree?
Heaps • Heap • A complete binary tree, each of whose elements contains a value that is greater than or equal to the value of each of its children Remember? Complete tree
Heaps Heap with letters 'A' .. 'J'
Heaps Another heap with letters 'A' .. 'J'
treePtr 50 C 30 20 A T 10 18 Heaps treePtr Are these heaps?
70 Heaps treePtr 12 60 40 30 8 10 Is this a heap?
70 Heaps Where is the largest element? treePtr 12 60 40 30 8 Can we use this fact to implement an efficient PQ?
Heaps • We have immediate access to highest priority item BUT if we remove it, the structure isn't a heap • Can we "fix" the problem efficiently?
Heaps Shape property is restored. Can order property be restored?
Heaps How?
Heaps template<class ItemType> struct HeapType { void reheapDown(int root, int bottom); … ItemType* elements; // Dynamic array int numElements; }
70 0 Heaps root Number nodes left to right by level 12 2 60 1 40 3 30 4 8 5
tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] 70 60 12 40 30 8 70 0 12 2 60 1 40 3 30 4 8 5 Heaps elements Use number as index
Heaps • ReapDown(heap, root, bottom) • if heap.elements[root] is not a leaf • Set maxChild to index of child with larger value • if heap.elements[root] < heap.elements[maxChild] • Swap(heap.elements[root], heap.elements[maxChild]) • ReheapDown(heap, maxChild, bottom) What variables do we need? Where are a node's children?
Heaps // IMPLEMENTATION OF RECURSIVE HEAP MEMBER FUNCTIONS void HeapType<ItemType>::ReheapDown(int root, int bottom) // Pre: ItemType overloads the relational operators // root is the index of the node that may violate the // heap order property // Post: Heap order property is restored between root and // bottom { int maxChild ; int rightChild ; int leftChild ; leftChild = root * 2 + 1 ; rightChild = root * 2 + 2 ;
Heaps if (leftChild <= bottom) // ReheapDown continued { if (leftChild == bottom) maxChild = leftChld; else { if (elements[leftChild] <= elements[rightChild]) maxChild = rightChild; else maxChild = leftChild; } if (elements[root] < elements[maxChild]) { Swap(elements[root], elements[maxChild]); ReheapDown(maxChild, bottom); } } }
Heaps • What other operations might our HeapType need?
Heaps Add K: Where must the new node be put? Now what?
void HeapType::ReheapUp(int root, int bottom) // Pre: ItemType overloads the relational operators // bottom is the index of the node that may violate // the heap order property. The order property is // satisfied from root to next-to-last node. // Post:Heap order property is restored between root and // bottom { int parent; if (bottom > root) { parent = ( bottom - 1 ) / 2; if (elements[parent] < elements[bottom]) { Swap(elements[parent], elements[bottom]); ReheapUp(root, parent); } } }
Heaps • How can heaps be used to implement Priority Queues?
Priority Queues • class FullPQ(){}; • class EmptyPQ(){}; • template<class ItemType> • class PQType • { • public: • PQType(int); • ~PQType(); • void MakeEmpty(); • bool IsEmpty() const; • bool IsFull() const; • void Enqueue(ItemType newItem); • void Dequeue(ItemType& item); • private: • int length; • HeapType<ItemType> items; • int maxItems; • };
Priority Queues • template<class ItemType> • PQType<ItemType>::PQType(int max) • { • maxItems = max; • items.elements = new ItemType[max]; • length = 0; • } • template<class ItemType> • void PQType<ItemType>::MakeEmpty() • { • length = 0; • } • template<class ItemType> • PQType<ItemType>::~PQType() • { • delete [] items.elements; • }
Priority Queues • Dequeue • Set item to root element from queue • Move last leaf element into root position • Decrement length • items.ReheapDown(0, length-1) • Enqueue • Increment length • Put newItem in next available position • items.ReheapUp(0, length-1)
Priority Queues • template<class ItemType> • void PQType<ItemType>::Dequeue(ItemType& item) • { • if (length == 0) • throw EmptyPQ(); • else • { • item = items.elements[0]; • items.elements[0] = items.elements[length-1]; • length--; • items.ReheapDown(0, length-1); • } • }
Priority Queues • template<class ItemType> • void PQType<ItemType>::Enqueue(ItemType newItem) • { • if (length == maxItems) • throw FullPQ(); • else • { • length++; • items.elements[length-1] = newItem; • items.ReheapUp(0, length-1); • } • }
Enqueue Dequeue Heap O(log2N) O(log2N) Linked List O(N) O(N) Binary Search Tree Balanced O(log2N) O(log2N) Skewed O(N) O(N) Comparison of Priority Queue Implementations
Graphs • Graph • A data structure that consists of a set of models and a set of edges that relate the nodes to each other • Vertex • A node in a graph • Edge (arc) • A pair of vertices representing a connection between two nodes in a graph • Undirected graph • A graph in which the edges have no direction • Directed graph (digraph) • A graph in which each edge is directed from one vertex to another (or the same) vertex
Graphs • Formally a graph G is defined as follows G = (V,E) • where V(G) is a finite, nonempty set of vertices E(G) is a set of edges (written as pairs of vertices)
Graphs Vertex Undirected Graphs have no arrows on the edges Edge or arc
Graphs Directed edge
Graphs What other structure is this ?
Graphs • Adjacent vertices • Two vertices in a graph that are connected by an edge • Path • A sequence of vertices that connects two nodes in a graph • Complete graph • A graph in which every vertex is directly connected to every other vertex • Weighted graph • A graph in which each edge carries a value
Graphs How many edges in a directed graph with N vertices? How many edges in an undirected graph with N vertices?
Graphs Weight
Graph Algorithms • Depth-first search algorithm • Visit all the nodes in a branch to its deepest point before moving up • Breadth-first search algorithm • Visit all the nodes on one level before going to the next level • Single-source shortest-path algorithm • An algorithm that displays the shortest path from a designated starting node to every other node in the graph
Graphs • Operations: The usual suspects • IsFull • IsEmpty • Initialize • Insert requires two operations • Add vertex • Add Edge • Others? Let's see.
Graphs DepthFirstSearch Set found to false stack.Push(startVertex) do stack.Pop(vertex) if vertex = endVertex Write final vertex Set found to true else Write this vertex Push all adjacent vertices onto stack while !stack.IsEmpty() AND !found if (!found) Write "Path does not exist"
Graphs Try depth first search from Austin
Graphs Do you see a problem? Do you have a solution?
Graphs • We need to "mark" a vertex as visited • ClearMarks • MarkVertex(VertexType, vertex) • Boolean IsMarked(VertexType, vertex)
Graphs BreadthFirstSearch Set found to false queue.Enqueue(startVertex) do queue.Dequeue(vertex) if vertex = endVertex Write final vertex Set found to true else if (vertex is not marked) Mark vertex Write vertex Get a queue of outgoing vertices from vertex while (vertexQ is not empty) vertexQ.Dequeue(Item) if (item is not marked) queue.Enqueue(item) while queue IsEmpty() AND !found if (!found) Write "Path does not exist"
Graphs Try depth breadth search from Austin
Graphs DFS uses a stack; BFS uses a queue