Chapter 9 Priority Queues, Heaps, Graphs 1 Fall 2010.

Slides:



Advertisements
Similar presentations
Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
Advertisements

1 A full binary tree A full binary tree is a binary tree in which all the leaves are on the same level and every non leaf node has two children. SHAPE.
CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
Abstract Data Types and Subprograms
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Abstract Data Types and Subprograms
Chapter 8, Part I Graph Algorithms.
Graphs CS3240, L. grewe.
1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
Advanced Data Structures
Priority Queues, Heaps CS3240, L. grewe 1. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe the.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Heaps CS 308 – Data Structures.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
Chapter 9 Heaps and Priority Queues. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape must.
Graphs CS 308 – Data Structures. What is a graph? A data structure that consists of a set of nodes (vertices) and a set of edges that relate the nodes.
CS 206 Introduction to Computer Science II 11 / 03 / 2008 Instructor: Michael Eckmann.
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 03 / 25 / 2009 Instructor: Michael Eckmann.
Using Search in Problem Solving
CS 206 Introduction to Computer Science II 11 / 09 / 2009 Instructor: Michael Eckmann.
Fall 2007CS 2251 Graphs Chapter 12. Fall 2007CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs To.
Important Problem Types and Fundamental Data Structures
9 Priority Queues, Heaps, and Graphs. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Heaps and Priority Queues CS 3358 – Data Structures.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets.
Graphs. What is a graph? A data structure that consists of a set of nodes (vertices) and a set of edges that relate the nodes to each other The set of.
Chapter 9 Priority Queues, Heaps, and Graphs. 2 Goals Describe a priority queue at the logical level and implement a priority queue as a list Describe.
9-1 Abstract Data Types Abstract data type A data type whose properties (data and operations) are specified independently of any particular implementation.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Common final examinations When: Wednesday, 12/11, 3:30-5:30 PM Where: Ritter Hall - Walk Auditorium 131 CIS 1166 final When: Wednesday, 12/11, 5:45-7:45.
Graphs. Definitions A graph is two sets. A graph is two sets. –A set of nodes or vertices V –A set of edges E Edges connect nodes. Edges connect nodes.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
Chapter 12 Abstract Data Type. Understand the concept of an abstract data type (ADT). Understand the concept of a linear list as well as its operations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
Chapter 8 Abstract Data Types and Subprograms. 2 Chapter Goals Distinguish between an array-based visualization and a linked visualization Distinguish.
1 Directed Graphs Chapter 8. 2 Objectives You will be able to: Say what a directed graph is. Describe two ways to represent a directed graph: Adjacency.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
CS 367 Introduction to Data Structures Lecture 8.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Heaps CS 302 – Data Structures Sections 8.8, 9.1, and 9.2.
Chapter 9 Heaps and Priority Queues Lecture 18. Full Binary Tree Every non-leaf node has two children Leaves are on the same level Full Binary Tree.
1 GRAPHS – Definitions A graph G = (V, E) consists of –a set of vertices, V, and –a set of edges, E, where each edge is a pair (v,w) s.t. v,w  V Vertices.
Section 9.6 Graph Applications. 9.6 Graph Applications Our graph specification does not include traversal operations. We treat traversal as a graph application/algorithm.
Chapter 9 Priority Queues, Heaps, and Graphs
Heaps (8.3) CSE 2011 Winter May 2018.
UNIT – III PART - II Graphs By B VENKATESWARLU, CSE Dept.
Bohyung Han CSE, POSTECH
UCS 406 – Data Structures & Algorithms
Chapter 9 Priority Queues, Heaps, Graphs, and Sets
Chapter 8 – Binary Search Tree
Tree Representation Heap.
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Graphs.
Yan Shi CS/SE 2630 Lecture Notes
Heaps and Priority Queues
Chapter 10 The Graph ADT.
Important Problem Types and Fundamental Data Structures
C++ Plus Data Structures
Chapter 9 The Priority Queue ADT
Heaps Chapter 6 Section 6.9.
Presentation transcript:

Chapter 9 Priority Queues, Heaps, Graphs 1 Fall 2010

Priority Queue 2 An ADT in which only the item with the highest priority can be accessed

Applications of Priority Queue 3  Telephone Answering System  Priority: the length of waiting (FIFO queue)  Airline Check-In System  Priority: Travel Class  Hospital Emergency Room  Priority: Severity of Injury

Implementation of a priority queue 9-4  There are many ways to implement a priority queue  An Unsorted List  Enqueue: O(1)  Dequeue: searching through the entire list O(N)  An Array-Based Sorted List  Enqueue: O(N)  Dequeue: O(1)  A Linked Sorted List  Enqueuing again is O(N)  Dequeue: O(1)  A Binary Search Tree  On average, O(log 2 N) steps for both enqueue and dequeue  Any other choice?

Heap 5 A complete binary tree, where each node contains a value that is greater than or equal to the value of each of its children

Heaps 6 Another heap with letters 'A'.. 'J'

Heaps 7 C A T treePtr Are these heaps? Shape & Order Properties treePtr

Heaps treePtr Is this a heap? Shape & Order Properties

Heaps treePtr Can we use this fact to implement an efficient Priority Queue? Where is the largest element?

Heaps 10  Heap is good choice for implementing Priority Queue.  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 11 Shape property is restored. Can order property be restored? How?

ReheapDown( ) 12  Function: Restores the order property of heaps to the tree between root and bottom.  Precondition: The order property of heaps is violated only by the root node of the tree.  Postcondition: The order property applies to all elements of the heap.

ReheapDown: illustration 13

ReheapDown() 14 If the root is not a leaf node If the value of the root is smaller than its largest child Swap the value of the root with the value of this child. ReheapDown the subtree with the new root value.  Why just compare the root with its children? How about the rest of the tree?  Precondition  Base Cases  The root of the current subtree is a leaf node.  The value of the root is greater or equal to the values in both its children.

Insert item into heap 15 Add ‘K’: Where must the new node be put? Shape Property is kept, but Order Property?

ReheapUp 16  Function: Restores the order property to the heap between bottom and root.  Precondition: The order property is satisfied from the root of the heap through the next-to-last leaf node; the last (bottom) leaf node violates the order property.  Postcondition: The order property applies to all elements of the heap from root through bottom.

17

If the root is not reached If the value of the bottom node is larger than the value of its parent Swap the value of the bottom node with the value of its parent ReheapUp the subtree with the new bottom node.  Why just compare the “bottom” node with its parent? How about the rest of the tree?  Precondition  Base Cases  Reach the root of the tree  The value of the bottom node is smaller or equal to the values of its parent. ReheapUp() 18

Heaps: how to store a heap? root Number nodes left to right by level

Implementation of Heaps tree [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] elements Use number as index bottom root

Review 21  For any node tree.nodes[index]  its left child is in tree.nodes[index*2 + 1]  its right child is in tree.nodes[index*2 + 2]  its parent is in tree.nodes[(index - 1)/2]

Heap: a data structure 22 struct HeapType { void ReheapDown(int root, int bottom); void ReheapUp(int root, int bottom); ItemType* elements; // Dynamic array int numElements; };

Recursive ReheapDown 23 void HeapType::ReheapDown(int root, int bottom) { int maxChild, rightChild, leftChild ; leftChild = root * ; rightChild = root * ; if ( leftChild < = bottom)//root has a left child, i.e., it is not a leaf node { //find the largest child if (leftChild == bottom) //only one child maxChild = leftChild; else { //find the larger child if (elements[leftChild].ComparedTo(elements[rightChild])!= GREATER) maxChild = rightChild; else maxChild = leftChild; } if (elements[root].ComparedTo(elements[maxChild])== LESS) //violates the order property { Swap(elements[root], elements[maxChild]); ReheapDown(maxChild, bottom); }

Recursive ReheapUp 24 void HeapType::ReheapUp(int root, int bottom) { int parent; if (bottom > root) //haven’t reached root yet { parent = ( bottom - 1 ) / 2; if (elements[parent].ComparedTo(elements[bottom])== LESS) { //violates the order property Swap(elements[parent], elements[bottom]); ReheapUp(root, parent); }

Heaps/Priority Queues 25  How can heaps be used to implement Priority Queues?  Enqueue()  Insert a node as the right-most leaf node  Apply the order property by calling ReheapUp()  Dequeue()  Remove the root node  Move the right-most leaf node to the root position  Apply the order property by calling ReheapDown()

Why Heap is Good 26  Heap’s Order Property:  Root has the largest value / highest priority  Heap’s Shape Property:  Min. number of levels with N nodes of a binary tree: log 2 N +1  A heap guarantees O(log 2 N) steps, even in the worst case  A complete tree is of minimum height.  At most log 2 N levels exist above the leaf node.  At most log 2 N levels exist below the root.

Comparison of Priority Queue Implementations 27 EnqueueDequeue HeapO(log 2 N) Linked ListO(N) Binary Search Tree BalancedO(log 2 N) SkewedO(N)

Graphs Graph A data structure that consists of a set of nodes and a set of edges that relate the nodes to each other Vertex A node in a graph Edge (arc) A connection between two nodes in a graph, represented by a pair of vertices. Adjacent vertices Two vertices in a graph that are connected by an edge 28

Graphs 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 29

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) 30

Graphs Vertex Edge or arc Undirected Graphs have no arrows on the edges 31

Graphs Directed edge 32

Graphs What other structure is this ? A tree is a acyclic graph. 33

Complete Graphs How many edges in a directed graph with N vertices? How many edges in an undirected graph with N vertices? 34 A graph in which every vertex is directly connected to every other vertex

Weighted Graphs Weight 35 A graph in which each edge carries a value

Array-Based Implementation Adjacency Matrix For a graph with N nodes, an N by N table that shows the existence (and weights) of all edges in the graph Mapping Array An array that maps vertex names into array indexes Marking Associate a Boolean variable with each vertex: true if visited, false if not yet visited 36

Adjacency Matrix for Flight Connections Where could marking variable be kept? 37

Linked Implementation Adjacency List A linked list that identifies all the vertices to which a particular vertex is connected; each vertex has its own adjacency list 38

Adjacency List Representation of Graphs Where could a marking variable go? 39

Graph Algorithms Breadth-first search algorithm Visit all the nodes on one level before going to the next level Depth-first search algorithm Visit all the nodes in a branch to its deepest point before moving up Single-source shortest-path algorithm An algorithm that displays the shortest path from a designated starting node to every other node in the graph 40

Graph Traversal  Visits all the vertices, beginning with a specified start vertex.  No vertex is visited more than once, and vertices are only visited if they can be reached – that is, if there is a path from the start vertex. 41

Breadth-First Traversal with Queue  “Neighbors-First”.  A queue data structure is needed. It holds a list of vertices which have not been visited yet but which should be visited soon.  When visiting a vertex, add its neighbors to the queue. Neighbors are not added to the queue if they are already in the queue, or have already been visited.  Queue: FIFO. 42

43 Graphs  We need to "mark" a vertex as visited  ClearMarks  MarkVertex(VertexType, vertex)  Boolean IsMarked(VertexType, vertex)

Graphs BFT result

45 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"

Depth-First Traversal with Stack  “Neighbors-First”.  A stack data structure is needed. It holds a list of vertices which have not been visited yet but which should be visited soon.  When visiting a vertex, adds its neighbors to the stack. Neighbors are not added to the stack if they are already in the stack, or have already been visited.  Stack: LIFO. 46

Graphs DFT result

48 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"

Breadth-First vs. Depth-First  Breadth-first Traversal: all one-flight solutions, then all two-flight solutions, etc. Austin Dallas Houston Denver Chicago Atlanta Washington 49

Breadth-First vs. Depth-First  Depth-first Traversal: keep going forward in one direction; backtrack only when reach a dead end. Austin Dallas Chicago Denver Atlanta Washington Houston 50

Single-Source Shortest-Path  A path through the graph is a sequence (v 1,..., v n ) such that the graph contains an edge e 1 going from v 1 to v 2, an edge e 2 going from v 2 to v 3, and so on.  Shortest-Path: the path whose weights have the smallest sum.  If the weight is the distance between two cities  shortest path: the route with minimum travelling distance.  If the weight is the travelling time between two cities  shortest path: the route with shortest travelling time. 51

Applications of Shortest Path Traversal  Google Maps finds the route with the shortest travelling time.  Networking Routing Protocols  Games 52

Dijkstra's Algorithm  Similar to Breath-First Traversal  A FIFO queue for unvisited neighbors of a visited vertex.  A priority queue for the possible path  Each item of the priority queue has three data members  fromVertex: last visited vertex on the path from the starting vertex  toVertex: next vertex to visit  Distance : the min. distance from the starting vertex to next vertex. 53

Dijkstra's Algorithm  The priority-queue implemented with a minimum heap  Starts from the Starting vertex, the first edge is itself (distance is 0).  For each visited vertex, put its unvisited neighbors into FIFO queue.  Dequeue the FIFO queue and put the possible path from the starting vertex to the neighbor into the priority queue.  Dequeue the priority queue one by one. 54

Graphs Start Here Washington -> Atlanta 600 Washington ->Dallas 1300 Washington -> Atlanta -> Houston 1400 Washington -> Dallas -> Austin 1500 Washington -> Dallas -> Denver 2080 Washington -> Dallas -> Chicago