SlideShare a Scribd company logo
1 of 29
DesignandAnalysisofAlgorithms
Dr.MohamedAhmedMohamedAli
University ofKhartoum
Faculty ofMathematical Sciencesand Informatics
29/8/2022 1
DesignandAnalysisofAlgorithms
GreedyTechnique
DynamicProgramming
•DynamicProgramming is ageneralalgorithm designtechnique
•InventedbyAmerican mathematicianRichard Bellmaninthe 1950stosolve
optimizationproblems
•“Programming” heremeans“planning”
•Mainidea:
•solveseveralsmaller(overlapping)subproblems
•recordsolutionsinatableso thateachsubproblem isonlysolvedonce
•finalstateofthetablewillbe(orcontain)solution
29/8/2022
DesignandAnalysisofAlgorithms
GreedyTechnique
2
Example:Fibonaccinumbers
•RecalldefinitionofFibonaccinumbers:
f(0)=0
f(1)=1
f(n)=f(n-1)+f(n-2)
•Computing the nth Fibonaccinumberrecursively(top-down):
• f(n)
f(n-1) + f(n-2)
f(n-2) + f(n-3) f(n-3) + f(n-4)
29/8/2022
DesignandAnalysisofAlgorithms
GreedyTechnique
3
Example:Fibonaccinumbers
Computing thenth fibonacci numberusing bottom-up iteration:
•f(0)=0
•f(1)=1
•f(2)=0+1=1
•f(3)=1+1=2
•f(4)=1+2=3
•f(5)=2+3=5
•
•
•f(n-2)=
•f(n-1)=
•f(n)=f(n-1) +f(n-2)
29/8/2022
DesignandAnalysisofAlgorithms
GreedyTechnique
4
ExamplesofDynamicProgramming
•Optimal chainmatrix multiplication
•Optimalbinarysearch tree
•Warshall’salgorithm fortransitiveclosure
•Floyd’salgorithmsfor all-pairsshortestpaths
•Someinstancesof difficult discreteoptimizationproblems:
•travellingsalesman
•knapsack
29/8/2022
DesignandAnalysisofAlgorithms
GreedyTechnique
5
Warshall’sAlgorithm
•Warshall’salgorithm forcomputing thetransitiveclosure ofadirectedgraph
29/8/2022
DesignandAnalysisofAlgorithms
GreedyTechnique
6
DesignandAnalysis ofAlgorithms
GreedyTechnique
7
Warshall’s Algorithm:TransitiveClosure
•Computes the transitiveclosureofarelation
•(Alternatively:allpathsinadirectedgraph)
•Exampleoftransitiveclosure:
3
4
2
1
0 0 1 0
1 0 0 1
0 0 0 0
0 1 0 0
0 0 1 0
1 1 1 1
0 0 0 0
1 1 1 1
3
4
2
1
29/8/2022
DesignandAnalysis ofAlgorithms
GreedyTechnique
8
Warshall’s Algorithm
•Main idea:apath existsbetweentwo verticesi,j,iff
•thereisanedgefromito j;or
•thereisapath fromitojgoingthroughvertex1;or
•thereisapath fromitojgoingthroughvertex1and/or 2;or
•thereisapath fromitojgoingthroughvertex1,2, and/or3;or
•...
•thereisapath fromitojgoingthroughanyoftheothervertices
3
4
2
1
3
4
2
1
3
4
2
1
3
4
2
1
R0
0 0 1 0
1 0 0 1
0 0 0 0
0 1 0 0
R1
0 0 1 0
1 0 1 1
0 0 0 0
0 1 0 0
R2
0 0 1 0
1 0 1 1
0 0 0 0
1 1 1 1
R3
0 0 1 0
1 0 1 1
0 0 0 0
1 1 1 1
R4
0 0 1 0
1 1 1 1
0 0 0 0
1 1 1 1
3
4
2
1
29/8/2022
DesignandAnalysis ofAlgorithms
GreedyTechnique
9
Warshall’s Algorithm
•Inthekth stage determine ifapathexistsbetween twovertices i,jusingjustverticesamong 1,…,k
R(k-1)[i,j] (path usingjust 1,…,k-1)
R(k)[i,j] = or
(R(k-1)[i,k] andR(k-1)[k,j]) (pathfrom itok
andfromkto i
usingjust 1,…,k-1)
i
j
k
kth stage
{
29/8/2022
DesignandAnalysis ofAlgorithms
GreedyTechnique
10
Floyd’s Algorithm:Allpairsshortestpaths
•Ina weightedgraph,findshortest pathsbetweeneverypairofvertices
•Sameidea:construct solutionthrough seriesof matricesD(0), D(1),… usingan
initialsubset of theverticesasintermediaries.
29/8/2022
DesignandAnalysis ofAlgorithms
GreedyTechnique
11
Floyd’s Algorithm:Allpairsshortestpaths
•Ina weightedgraph,findshortest pathsbetweeneverypairofvertices
•Sameidea:construct solutionthrough seriesof matricesD(0), D(1),… usingan
initialsubset of theverticesasintermediaries.
•Example:
3
4
2
1
4
1
6
1
5
3
29/8/2022
DesignandAnalysis ofAlgorithms
GreedyTechnique
12
FinalComments
•Dynamicprogramming isatechnique for solvingproblems withoverlapping sub-
problems.
•Applicabilityofdynamicprogramming toanoptimizationproblem requiresthe
problemtosatisfytheprinciple ofoptimality:anoptimal solutionto anyofits
instancesmustbemadeupofoptimalsolutionstoitssub-instances.
•Warshall’salgorithmfor findingthetransitiveclosureandFloyd’s algorithm for
theall-pairsshortest-paths problemarebasedontheideathat anbeinterpretedas
anapplicationof thedynamicprogramming technique.
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 13
GreedyAlgorithms
Optimizationproblemssolvedthrough a sequenceofchoicesthatare:
 feasible
 locallyoptimal
 irrevocable
Notalloptimizationproblemscan beapproached inthismanner!
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 14
ApplicationsoftheGreedyStrategy
 Optimalsolutions:
• changemaking
• MinimumSpanningTree(MST)
• Single-sourceshortest paths
• simpleschedulingproblems
• Huffmancodes
 Approximations:
• TravelingSalesmanProblem(TSP)
• Knapsackproblem
• other combinatorialoptimization problems
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 15
MinimumSpanningTree(MST)
 Spanningtreeof aconnectedgraph G:a connectedacyclic subgraph of Gthat
includesallof G’svertices.
 MinimumSpanningTreeofaweighted,connectedgraph G:aspanningtreeof
Gof minimumtotalweight.
 Example:
3
4
2
1
4
2
6
1
3
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 16
Prim’sMSTalgorithm
 Startwithtreeconsistingof onevertex
 “grow” treeonevertex/edgeatatimetoproduce MST
 Construct aseries ofexpandingsubtreesT1,T2,…
 ateachstage construct Ti+1 from Ti:addminimumweightedgeconnecting a
vertexintree(Ti)toonenotyetintree
 choose from “fringe”edges
 (thisisthe“greedy”step!)
 algorithmstops whenallverticesareincluded
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 17
Prim’sMSTalgorithm
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 18
Examples:
a
e
d
c
b
1
5
2
5 6
3 7
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 19
NotesaboutPrim’salgorithm
• Need toprovethat thisconstruction actuallyyieldsMST
• Need priorityqueue forlocatinglowest costfringeedge:use min-heap
• Efficiency: Forgraphwithnverticesandmedges:
(n–1+m)logn
Θ(mlog n)
numberofstages
(min-heap deletions) numberofedgesconsidered
(min-heapinsertions)
insertion/deletion frommin-heap
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 20
Another Greedyalgorithm forMST:Kruskal
 Startwithemptyforest of trees
 “grow” MST oneedgeatatime
• intermediatestagesusuallyhaveforestoftrees(notconnected)
 ateachstageaddminimumweightedgeamong thosenotyetusedthatdoesnot
createacycle
• edgesareinitiallysorted byincreasingweight
• ateachstagetheedgemay:
– expand anexisting tree
– combinetwo existing treesinto asingletree
– createanewtree
• needefficientwayofdetecting/avoidingcycles
 algorithmstops whenallverticesareincluded
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 21
Examples:
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 22
NotesaboutKruskal’salgorithm
 AlgorithmlookseasierthanPrim’sbutis
• hardertoimplement(checking forcycles!)
• lessefficient Θ(mlogm)
 Cyclechecking:acycleexistsifedgeconnectsverticesinthesame
component.
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 23
Shortestpaths-Dijkstra’salgorithm
 SingleSourceShortestPathsProblem:Givenaweightedgraph G,findthe
shortest pathsfrom a source vertexs toeachof theother vertices.
 Dijkstra’salgorithm:SimilartoPrim’sMSTalgorithm,withthefollowing
difference:
• Startwithtreeconsisting ofonevertex
• “grow”tree onevertex/edgeatatimetoproduce MST
– ConstructaseriesofexpandingsubtreesT1,T2,…
• Keep trackofshortest pathfromsourcetoeachoftheverticesin Ti
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 24
Example:
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 25
NotesonDijkstra’salgorithm
 Doesn’t workwith negativeweights
 Applicabletobothundirectedanddirectedgraphs
29/8/2022
DesignandAnalysis ofAlgorithms
GreedyTechnique
26
Huffman’salgorithm
 Step 1 Initialize n one-node trees and label them with the symbols of the
alphabet given. Record the frequency of each symbol in its tree’s root to indicate
the tree’s weight. (More generally, the weight of a tree will be equal to the sum of
the frequencies inthe tree’sleaves.)
 Step 2 Repeat the following operation until a single tree is obtained. Find two
trees with the smallest weight. Make them the left and right subtree of a new tree
andrecord the sumof theirweights inthe rootof thenewtreeasitsweight.
29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 27

29/8/2022
DesignandAnalysis ofAlgorithms GreedyTechnique 28
Assignment
 WriteKruskal’salgorithmto find aminimumspanningtreeforagivengraph
 Writepseudocode ofthe Huffman-treeconstruction algorithm.

29/8/2022
Design and Analysis of Algorithms Greedy Technique 29
END
29/8/2022

More Related Content

Similar to Lec7.ppt

Computational geometry
Computational geometryComputational geometry
Computational geometry
murali9120
 
Fast optimization intevacoct6_3final
Fast optimization intevacoct6_3finalFast optimization intevacoct6_3final
Fast optimization intevacoct6_3final
eArtius, Inc.
 
Dynamic programming class 16
Dynamic programming class 16Dynamic programming class 16
Dynamic programming class 16
Kumar
 

Similar to Lec7.ppt (20)

Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm Analysis
 
Learning to Compose Domain-Specific Transformations for Data Augmentation
Learning to Compose Domain-Specific Transformations for Data AugmentationLearning to Compose Domain-Specific Transformations for Data Augmentation
Learning to Compose Domain-Specific Transformations for Data Augmentation
 
Chapter one
Chapter oneChapter one
Chapter one
 
Unit i
Unit iUnit i
Unit i
 
Computational geometry
Computational geometryComputational geometry
Computational geometry
 
Fast optimization intevacoct6_3final
Fast optimization intevacoct6_3finalFast optimization intevacoct6_3final
Fast optimization intevacoct6_3final
 
Convex optmization in communications
Convex optmization in communicationsConvex optmization in communications
Convex optmization in communications
 
L01 intro-daa - ppt1
L01 intro-daa - ppt1L01 intro-daa - ppt1
L01 intro-daa - ppt1
 
1 resource optimization 2
1 resource optimization 21 resource optimization 2
1 resource optimization 2
 
PR-272: Accelerating Large-Scale Inference with Anisotropic Vector Quantization
PR-272: Accelerating Large-Scale Inference with Anisotropic Vector QuantizationPR-272: Accelerating Large-Scale Inference with Anisotropic Vector Quantization
PR-272: Accelerating Large-Scale Inference with Anisotropic Vector Quantization
 
Complexity Analysis
Complexity Analysis Complexity Analysis
Complexity Analysis
 
Senior Project4-29
Senior Project4-29Senior Project4-29
Senior Project4-29
 
Compositional Program Analysis using Max-SMT
Compositional Program Analysis using Max-SMTCompositional Program Analysis using Max-SMT
Compositional Program Analysis using Max-SMT
 
Dynamic programming class 16
Dynamic programming class 16Dynamic programming class 16
Dynamic programming class 16
 
Constraint Programming - An Alternative Approach to Heuristics in Scheduling
Constraint Programming - An Alternative Approach to Heuristics in SchedulingConstraint Programming - An Alternative Approach to Heuristics in Scheduling
Constraint Programming - An Alternative Approach to Heuristics in Scheduling
 
PF_MAO2010 Souma
PF_MAO2010 SoumaPF_MAO2010 Souma
PF_MAO2010 Souma
 
Quantum Business in Japanese Market
Quantum Business in Japanese MarketQuantum Business in Japanese Market
Quantum Business in Japanese Market
 
Georgetown B-school Talk 2021
Georgetown B-school Talk  2021Georgetown B-school Talk  2021
Georgetown B-school Talk 2021
 
Simulation Watch Window Part I.pdf
Simulation Watch Window Part I.pdfSimulation Watch Window Part I.pdf
Simulation Watch Window Part I.pdf
 
Graph Gurus Episode 26: Using Graph Algorithms for Advanced Analytics Part 1
Graph Gurus Episode 26: Using Graph Algorithms for Advanced Analytics Part 1Graph Gurus Episode 26: Using Graph Algorithms for Advanced Analytics Part 1
Graph Gurus Episode 26: Using Graph Algorithms for Advanced Analytics Part 1
 

Recently uploaded

Recently uploaded (20)

An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 

Lec7.ppt