Week06 DP 2
Week06 DP 2
Special acknowledgement to School of Computing, National University of Singapore for allowing Steven to prepare and distribute these teaching materials.
CS3233 CompetitiveProgramming p g g
Dr.StevenHalim Dr. Steven Halim Week06 ProblemSolvingParadigms
(DynamicProgramming2) (D i P i 2)
Outline
MiniContest#5+Break+Discussion+Admins AsimpleproblemtorefreshourmemoryaboutDPparadigms DPanditsrelationshipwithDAG(Chapter4)
DPonExplicitDAG/ImplicitDAG
Th TheseareCS2020/CS2010materials CS2020/CS2010 t i l ThosefromCS1102mustcatchup/consultStevenseparately
NONCLASSICALDPPROBLEMS
TimeComplexity:Therecanbeupto50possiblecuttingpoints, thusmax2500x50=125000operations,doable
000 000
025 025
075 075
100 100
DPonDAG(1) ( )
Overview DynamicProgramming(DP)hasacloserelationship with(sometimesimplicit)DirectedAcyclicGraph(DAG)
Thestates arethevertices oftheDAG Spacecomplexity:NumberofverticesoftheDAG Thetransitions aretheedges oftheDAG
Logical,sincearecurrenceisalwaysacyclic
DPonDAG(2) ( )
OnExplicitDAG(1) ThereisaDAGinthisproblem(canyouspotit?)
UVa 10285 (LongestRunonaSnowboard)
GivenaR*Cofheightmatrixh, findwhatisthelongestrunpossible?
Longestrunoflengthk:
h(i1,j1)>h(i2,j2)>>h(ik,jk)
LongestpathinDAG!
WewilllearnacreativeDPtablefillingtechnique g q fromthisshortexample(bottomup)
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS
DPonDAG(2) ( )
OnExplicitDAG(2)
Completesearchrecurrence:
Leth(i,j)=heightoflocation(i,j) Let f(i j) longest run length started at (i j) Letf(i,j)=longestrunlengthstartedat(i,j) f(i,j)=1+max(fvaluesofreachableneighbors:h(i,j)>h(neighborsi,j))
Basecase:Ifh(i,j)isthelowestamongitsneighbor,thenf(i,j)=1
DoitfromallpossibleR*Clocations!
Doyouobservemanyoverlappingsubproblems?
Thisproblemisactuallysolvableusingcompletesearchdue to smallR*C+constraints!
ButwithDP,thesolutionismoreefficient
AnditcanbeusedtosolvelargerR*C
DPonDAG(2) ( )
OnExplicitDAG(3) FillintheTable(BottomUp)Trick:
Sort(i,j)accordingtoh(i,j)inincreasingorder
i.e.Fillthebottomcellsfirst! Fillinf(i,j)inorderbasedonthevalueof f(i 1,j),f(i+1,j),f(i,j 1),f(i,j+1) f(i1 j) f(i+1 j) f(i j1) f(i j+1)
Thisisthetopologicalsort!
Thismayactuallybehardertocode
Forthisproblem,writingtheDPsolutionintopdownfashion maybebetter/easier
DPonDAG(3) ( )
ConvertingaGeneralGraph DAG(1)
Noteverygraphproblemhasareadyalgorithmforit
SomehavetobesolvedwithCompleteSearch Some are solvable with DP as long as we can find a way to make the SomearesolvablewithDP,aslongaswecanfindawaytomakethe DPtransitionacyclic,usuallybyaddingone(ormore)parametersto eachvertex :O RememberthatDijkstrasisagreedyalgorithm,andeverygreedy solution(withoutproofofcorrectness)hasachanceforgettingWA
DP+BITMASK ANDTIPS/TRICKS
Subproblems,breaktheoriginalprobleminto
SubproblemandPrefix:[x1,x2,,xn1]+xn Suffixandsubproblem:x1 +[x2,x3,,xn] Two sub problems: [x1,x2,,xi] + [xi+1,xi+2,,xn] Twosubproblems:[x x x ]+[x x x
Example:LIS,1DMaxSum,MatrixChainMultiplication ( (MCM),etc ),
Subproblems,breaktheoriginalprobleminto
Subproblemandprefix:[x1,x2,,xn1]+xn and[y1,y2,,yn1]+yn S ffi Suffixandsubproblem:x1 +[x2,x3,,xn] d 1 +[y2,y3,,yn] d b bl [ ]andy [ Twosubproblems: [x1,x2,,xi]+[xi+1,xi+2,,xn]and [y1, y2, , yi] +[yi+1, yi+2, , yn] ,y ,,y ] [y ,y ,,y
Example:StringAlignment/EditDistance,LCS,etc PS: Can also be applied on 2D matrix, like 2D Max Sum, etc PS:Canalsobeappliedon2Dmatrix,like2DMaxSum,etc
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS
InICPC/IOI: /
Ifactualsolutionsarenotneeded(onlyfinalvaluesasked)
Ifwemustcomputethesolutionstoo,amorecomplicatedDPwhich storespredecessorinformation andsomebacktracking arenecessary stores predecessor information and some backtracking are necessary
Theymayhavesubproblemsbutnotoverlapping
DPdoesnotworkifoverlappingsubproblemsnotexist
Anyway,thisisstillagoodnewsasperhaps DivideandConquertechniquecanbeapplied d d h b l d
Therecanbemorethanonepossibleformulation
Picktheonethatworks!
Thesenewproblemsarenot theclassicalDP!
Theyrequiredeepthinking Orthosethatlooksolvableusingother(simpler) g ( p ) algorithmsbutactuallymustbesolvedusingDP DonotthinkthatyouhavemasteredDP byonlymemorizingtheclassicalDPsolutions!
BymasteringGraph+DP,yourICPCrankisprobably:
fromtop~[2530](solving12problemsoutof10) p [ ]( g p )
Onlyeasyproblems
totop~[1020](solving35problemsoutof10)
Easyproblems+somegraph+greedy/DPproblems
BEAPROBLEMSETTER
ProblemSetter:
A. Writeagood problem B. Writegood B Write good solutions
Thecorrect/bestone Theincorrect/slowerones
Writegood solutions
Mustbeabletosolve yourownproblem!
Tosethardproblem, onemustincreasehis one must increase his ownprogrammingskill!
Problemdescription mustnotbeambiguous
Specif inp t constraints Specifyinputconstraints GoodEnglish! y g , Easyone:longer, Hardone:shorter!
Setproblemsettings
TimeLimit:
Usually2or3timesthe timingsofyourown bestsolutions
JavaslowerthanC++!
L Largetestcasesto t t t checkACvsTLE/MLE
Perhapsuseinput Perhaps use input generatortogenerate largetestcase,then passthislargeinputto pass this large inp t to ourcorrectsolution
MemoryLimit:
CheckOJsetting^ Avoidrevealingthe algorithminthe p problemname
ProblemName:
Deliverables:
1html:problemdescription+sampleI/O 1 html: problem description + sample I/O 1sourcecode:cpp/java 1testdatafile(ofmultipleinstancestype) ( p yp ) 1shorttxtwriteupoftheexpectedsolution ZipanduploadyourproblemintospecialfolderinIVLE
CS3233/Homework/BeAProblemSetter
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS
IntroductiontoAlgorithms,p323369,Ch15 AlgorithmDesign,p251 336,Ch6 Algorithm Design, p251336, Ch 6 ProgrammingChallenges,p245267,Ch11 http://www.topcoder.com/ htt // t d / tc?module=Static&d1=tutorials&d2=dynProg Bestispractice&morepractice!