Transcript

Use with ChatGPT / Claude Auto-scroll A

1. Chapter 1 (0:12)

0:12 - 1:09
all right welcome to the grand finale of dynamic programming in 6006 four of four today we are going to focus in on a particular type of sub problem that we saw at the very beginning with fibonacci which iswhen you have an integer input and a natural thing to do with that integer input is look at smaller versions of that integer and this is going to lead us to a new notion called pseudo-polynomial time we've talkeda lot in this class about polynomial time being a good running time but pseudopolynomial is a pretty good running time and we'll talk about that and it relates to these integers we'll only look at two exam new examplesrod cutting and subset sum but then we're going to review all the examples we've seen from kind of diagonal perspective so uh as usual we're applying our swordbot framework with subproblems relations topological order base cases original problem and
time quick review uh we saw so the hardest part is getting the right set of sub problems uh and there are some natural choices for sequences we try prefixes suffixes substrings for integers like in fibonacci there's a givennumber and you want to compute that at the nth fibonacci number what we ended up doing was solving fibonacci numbers for all input numbers input integers between 0 and that number n or in this case capital k andthat's a general technique and we'll see two more examples of that today otherwise we take products of these and often that's enough but sometimes we need to add more sub problems in what we call sub problem expansion oftenwith extra constraints that let us remember some state about the past my canonical example that is the piano fingering where we had to remember what our fingering assignment was in some sense from the previous step in order to
compute the transition cost and this is very powerful technique you can also use it to like play super mario brothers optimally if you have a constant size screen and all you need to remember is what's in the constantsize screen if everything outside that screen resets you can just add that state as a parameter to your sub problem and you'll be able to solve solve super mario brothers anyway very very useful and that was sort ofthe focus of last lecture we won't talk about it much here today and then we relate these sub problems recursively and this is basically the test of whether your sub problem definition was correct is can you write downa recurrence relation which is just a recursive algorithm and there's a nice general procedure for how to come up with these relations which is to just think up some question about the sub-problem solution that if you knew the
answer reduced to smaller sub-problems and then you just locally brute force all the answers to that question which i like to think of as guessing the answer correctly and then just directly calling the recursive things but then atthe end you have to pay for that guess by looping over all possible guesses in order to guarantee that you actually find the right oneso once you identify this question it's very easy dp is all about just brute force anything that you want and usually that leads to pretty good running time as long as the number of possible answers to that questionis polynomial then we need to check this relation is acyclic and then it it's often reduces to finding a path like a shortest path or something in a dag the subproblem dag uh we need some base cases weneed to make sure we can solve the original problem using one or more sub problems and then we analyze the running time as usually a number of subproblems times the amount of non-recursive work in the relation plus however
much time it took us to solve the original problem okay so that was our framework we've seen it four times now slightly refined each time we've mostly added some general techniques for sub problem definition and how to writerelations
so let's do a new example which is rod cuttingthis will be pretty straightforward but it will serve as a contrast to the next example we talked about subset sum so what is the problem the name rod coming comes from the book clrs but it's actually a prettypractical problem maybe not for cutting rods but you could imagine you you have some resource of a given length i like to think because i have been uh wood hardwood shelf shopping recently i like to think of youhave a big plank of hardwood and you get some price for selling that length but you could also cut that plank into multiple pieces of various lengths that sum to l and you could sell them individually maybe youmake more money that way that's what this problem is all about so you're given the value of every possible length you could cut we're going to assume all links have to be integers and scale so that that's

2. Chapter 2 (5:22)

true
so capital l here is the original length little l is a candidate length of a piece you might cut and v of l is the value for cutting off a length uh l rod sub rod and we're goingto assume when we cut we don't lose any material uh you could probably adjust for that but it's not terribly interesting and we want to know what is the best way to split up our big rod of lengthcapital l into various rods of small l length different potentially different lengths so i'll call this the max value partition in mathematics this is called partition a bunch of numbers that sum to a given number
and we want to maximize the total value naturally so here's an example
let's say our original length is seven and we have this table for lengths one two three four five six seven all the different lengths i'm going to write down a value that's an integer cutting off a route ofthat length and selling it select sell price it's presumably monotonic but doesn't have to be maybe people really like buying powers of two length or something and so those sell higher so it doesn't have to be monotonic butin this example it is and so i have this route of length seven and i could sell it directly for 32 dollars let's say but i could also split it into say uh one a length one rod anda length six or a length one rod and two length threes or a length three and a four anything that sums to seven and probably the most natural thing to do for this problem is like a heuristic this
would be a greedy bang for buck heuristic is what it's usually called is to take the ratio how much money do i get for a given length divide v of l by l and try to maximize that thatwould sort of be if i had to pick a single item and sell many of that type that would be the optimal thing to do so this has a ratio of one that's bad this has a ratio offive that's better and you stare at it long enough i believe six is the best has the highest ratio slightly more than uh i can't divideum slightly better than um let's see slightly slightly worse than four or was fourth the best
slightly worse than four what do you mean

3. Chapter 3 (8:30)

oh slightly i see the ratio is slightly less than four thank you yeah uh which all of these others are somewhat worse for example two uh if i double the 3 value i get 26 which is quite abit less than 31 and i guess the the closest competitor i think is 2 because if you multiply this by 3 you get 30.so if i sold three twos i get 30 but if i sell one six which is the same quantity i get 31 so slight improvement and so this this item maximizes bank for buck that ratio and so onenatural partition is six plus one i sell one rod of length six and that leaves a rod of length one and this will give me uh 31 for the six and one dollar which gives me 32 dollars uhbut this turns out to not be the best which is actually the same as if you just sold it outright but in fact you can do better by selling this is not obvious stare at it for a while
a three and a four also sums to 7 then we get 13 plus 18 which is hopefully bigger 33 30 get this right nope i did not get it right uh that's too small uh we're going to takethese two and sell 3 plus 2 plus 2.then i get 13 plus 10 plus 10 remember two was a close competitor first for the ratio for six so it's a little better to sell twos two twos and then a three because then we get thirty threedollars and that turns out to be the best for this problem and it seems really tricky to figure this out in general there are exponentially many different partitions can't afford to try them all question can i have negativevalues can i have negative values in here uh i think that will work fine i'm not allowed to have negative lengths or zero lengths i don't want zero length to actually give you something because then i just cut
infinitely many zeros but uh the v of l i think could be negative yeah do i have to use a whole bar uh in this problem yes i think it wouldn't change much if you didn't have to usethe whole bar we can think about those after we write the dp so um let's solve this with sort bot
so what's the input to this problem well we have uh i didn't mention this is an integer length
positive integer length
so we have one input which is an integer l and we have another input which is i guess it's like an array of integers so this is a sequence and this is an integer so if we look atour list of nice sub problems we could try prefixes or suffixes or substrings of the value structure or we could try for that integer smaller integers that's actually what i prefer i think the way to think about thisis to jump ahead to what do we want to what feature of the solution do we want to guess and presumably we should think about what is some length of rod that we will cut and sell okay soi have this big rod maybe i sell the whole thing maybe i cut off a thing of size one and sell it maybe i cut off a thing of size two and sell it um but i have to
sell something unless i'm not selling anything and so uh that's there's only n different or there's only l different choices for what uh rod lengths to cut off first and so we can just brute force that in orderl time so what problem do we get if we cut off an integer of some small l length well we just get the same problem with a rod of length capital l minus small l the values don't changeit happens that i won't use the big values if i cut off some amount of the the problem but i like to think of this as we're just all we're doing is decreasing big l and so my subproblems are going to be uh for each small l less than or equal to big l solve that problem so x of l is max value

4. Chapter 4 (13:18)

partition of uh length l little l for little l equals zero one up to big l okay so just same problem but with different choices for big l so this is using this integer sub problem now in thisexample that happens to correspond to prefixes of the v array because if i only have length up to little l that i really only need the prefix of the value array up to little l so you could thinkof it that way that's also fine but i think this way is a little more generalizable okay so i claim this is a good set of sub problems because i can write a recurrence relation which is actually prettysimple
like i said uh we want to choose
some piece so we're given a rod of length little l i want to choose how much of that rod to sell in the next piece so i could cut off something of length one or i could sell thewhole thing or cut off any piece size in between and the money i will get for that is whatever the value of that piece is plus recursively the maximum i can get from all the remaining pieces sorry fromthe remaining length which is little l minus p okay so very simple inside the formula just the value for the first piece we're guessing what is the first piece we'll cut off and sell we get the value forthat piece and then recursively we see what's the best we can do with the remainder now we don't know what size the first piece should be so we just brute force it we try all possible choices for p
and take the max that we get out of this formula over that choice and that's guaranteed to find the best overallbecause we must cut off some piece now if you wanted to allow not selling anything in the case of negative numbers you could just add a zero to this max and then you might stop early if there's nothingleft that's worth
selling okay topological order is very simple we just have these capital l different problems and if you look at oh uh yep so we're looking at l minus p p is always at least one so we're always strictlydecreasing l in this recursive call and so as long as i solve the problems in order of increasing little l i'll guarantee that whenever i'm solving x of little l i'll have already solved all the things i needto call so if you're writing a bottom up dp this would just be the for loop l equals zero up to big l in that order this is equivalent to the statement but the key is to check thatthis is acyclic because we're always referring to smaller l and so increasing l is a valid topological order in this sub-problem uh dag defined here where there's an edge from an earlier thing to evaluate to a later thing
to evaluate okay base casewould be x of zero that's the first thing we'll want to compute here and indeed this formula doesn't make much sense if i have x of 0 because i can't choose a number p between 1 and 0.even non-strictly and so what does it mean well if i have a rod of length 0 i can't get any money out of it so that's it it's a 0.that's an assumption but a reasonable assumption you don't get something for nothing okay then we have the original problem which is just the length l rod and then the time to compute this thing how many sub problems arethere capital l plus one so we'll say theta l sub problems
and we'll multiply by uh the amount of time to evaluate this max just a constant number of things in here not counting the recursive call and so it spent takes little l time little l is certainly at mostbig l and so we'll say big o of big l time it's actually a triangular number but it will only affect things by a constant factor so we get l squared time
and we're done so very simple straightforward dp at this point we've seen much more complicated examples than this but it highlights a question which is is uh theta l squared polynomial

5. Chapter 5 (18:40)

time so is this a reasonable running time and i claim the answer is yes this is a reasonable polynomial running time you might say well of course it's a polynomial look this is a polynomial l squared that's aquadratic polynomial but it's a quadratic polynomial in l and we haven't really thought about this too hard but what does it mean to be polynomial time um and this is a notion that's properly called strongly polynomial time wewon't worry about that strongly too much in this class but if you look this up online you'll see the difference polynomial time means that the running time is polynomialin the size of the inputand the size of the input is for our model measured in wordsmachine words remember our good old word ram w bit words it's been very useful because it lets us assume things like adding two numbers is constant time as long as these numbers fit in a word as long as
they're at most w bits and generally we assume all the things we're manipulating fit in a machine word because that's what the case where we normally work and so the natural way to imp to measure the size ofan input so in this example this problem rod cutting the input is a single number l and this value array v of l which is capital l numbers so i would say n integers and we've generally assumed didn'tmention integer value here as in throughout this class we assume that all the integers unless otherwise specified fit in a word so we've got one word here and l words here so the total size of the input tothis problem is l plus one integers in this problem input size is l plus one which we can think of as just l that means theta l okay so i explicitly didn't want to use n in this problem
because usually we use the letter n for the problem size not quite always but input size always means input size and so here we can compute it in terms of the specification it involves l plus one word inputsand so polynomial time should be polynomial in that input size in l plus one in our example so of course l squared is polynomial and l plus one so good yes okay the next example i'm going to showis going to be very similar but the answer will be no make it more interesting but it'll still seem pretty reasonable so we'll come back to that issue in a moment let me first show you uh what thesubproblem dp looks like for this problem again took me a while to draw so please admire so this is the same example of of these values 1 10 13 18 20 31 32 drawn here on a graph it's
the complete graph oriented uh in this increasing way i think this is called a tournament in graph theory uh so we have the base case over here uh this corresponds to a length zero rod where we get nomoney and over here we have our full rod of length seven and i claim the best that we can do is uh 33 and what's happening here is for every value like three that i could sell a rodof length three for 13 there's an edge that goes from each vertex to 1 3 higher and those all have a weight of 13 on them and then what we're essentially trying to do is find a longest pathfrom here to here longest because we want to maximize the sum of values that we get and we know if we negate all the weights that's the shortest path problem so we could solve that with shortest paths in
a dag but i've drawn here the shortest path tree from the base case um so it actually tells us that if we had a rod of length seven the best thing to do is to sell it directly forthirty one the bold lines here are the shortest path tree or the longest path tree i guess and if we had something in length 10 we should sell it directly if we have something of length 20 we shouldsell one thing of length 2 and another thing of left sorry one thing of length 4 then we should sell one thing of length 10 of 2 and one of length two we get two times ten points andfor the 33 case we sell one thing of length two one thing of length two and then one thing of length three is optimal so you can read lots of information from this and if you write down the
dp code this is effectively what it's computing from left to right
okay let's move on to our second problem today which is subset sum

6. Chapter 6 (24:02)

so here we are given
let's say a multi-set
multiset means that i can repeat numbers so this is just a sequence of numbers but i'd like to use set notation because i want to use subsets because it's subset sum um so this is of n integers
and we're also given a target sum

7. Chapter 7 (24:43)

and we want to know does any subset
sum to the target sum
this is actually a similar problem to rod cutting because rod cutting we also had to split up our number l into different values that summed to capital l so capital t here is playing the role of capital lbut before we were allowed to cut into any lengths and so it was easy in particular l sums to l here presumably t is not in this multiset and we need to find a combination of numbers here thatadd up exactly to t sometimes that's possible sometimes it's not we're only allowed to use each number once or as many times as it appears in the subset okay so here's an example
say a equals two five seven eight nine uh and two examples are t equals 21 and t equals 25 for that same set so can i get 21 out of these well this involves arithmetic that's hard i thinklet's see if i add 7 and 8 i get 15 not quite what i want cheat look at my answer uh yeah close i see five seven nine uh so this is a yes answer to the question doesthere exist any subset because uh 5 7 and 9 sum to exactly 21 and t equals 25 i don't know a good way to prove to you that there's no way to write 25 with these numbers other thani wrote a program that tried all subsets and or you could write a program that runs the dp that we're about to give and it will output no there's no succinct way as far as we know to prove
to someone that the answer is no for a given target sum there is a nice succinct way to prove the answer is yes i just give you a subset we'll talk more about that next lecturebut these are some examples of the question you might ask and the answer that we're looking for this is what we call a decision problem in its original form we're just interested in a yes or no answer uhit's a single bit
of course in the yes case we might actually want to find the set and we can do that as usual with parent pointers just like in the bold lines over here we'll get to that in a moment umbut this is a little bit different from the most the problems we've been seeing with dynamic programming are optimization problems and we're trying to minimize or maximize something and so we always put a min or a max onthe outside in the relation here we're going to have to do something that involves boolean values yes or no true or false okay so let's solve it this is actually also going to be pretty straightforward um in thatwe can just use our standard sets of subproblems so just like the previous problem we have on the one hand a sequence of integers and on the other hand we're given a single integer t and what turns out
to be right is to use prefix prefixes or suffixes on this sequence and uh integers less than or equal to t let's think about why

8. Chapter 8 (28:38)

so that was sort bot for rod cutting this is swordbot for subset sum
again i'll look for a look ahead to what feature of the solution should i guess well i have these n numbers each of them could be in my subset or not so i have this binary choice for eachai is it in s or not that's a lot of questions to answer i can't answer them answer them all at once but i could just start with the first one and say well is a 0 an syes or no there's two answers locally brute force if i do that what happens to my problem what new sub problems do i run into what do i want to recurse on well i've eliminated a zero that willleave a suffix of the ai's so suffixes on capital a seem like a good idea and what about my target sum well it depends if i put a zero in my set s then the target sum for the
remainder is t minus a0 so t went down and so i need i need in my sub problems to represent smaller target sums also so this is how you figure out what sub problems you should use don't youi mean you could just try prefixes on this suffixes on this substrings on this and yes or no do i include smaller versions of t here but you can also just think about try to write a recurrence relationfirst see what things you are naturally recursing on and then formulate the sub problems that way so that's what i like to doso i'm going to have a sub problem for each suffix uh so that's x of i and for each target sum and i use these capital letters for the for the actual target sum so that i can uselowercase letters for smaller versions of them so this is going to be uh does any subset remember don't first most important thing is to define what your sub problems are don't just say it's the same problem but where
i replace blah blah blah very it can be very ambiguous and so uh does any subset s of the suffix a from i onwards some to little tand we're going to have this sub problem the other important thing is to say how many sub problems there are and what your indices can vary over so i is going to be between 0 and n and tis going to be between 0 and big t okay so number of sub problems is n plus one times t plus one or theta n times t cool now i claim i can write a relation like i saidby so we have this suffix from a from i onwards in a and so i'm just going to because i'm looking at suffixes i want to keep with suffixes so i should try to guess what happens to aof i because then what will remain is a of i plus 1 onwards and a of i can either be in my subset s or not so there's two choices so x of i t is going to be
involve two things so there's an operator here and then i have a set of two items which is uh i could choose to not put a of i in my subset in that case i've eliminated a of iand what remains is uh a of i plus 1 onwards and i didn't change my target sum i i haven't put anything in s so i still want to achieve the same sum so this is the case wherea i is not in s and then the other case is i put a of i in s in that case again i've eliminated a of i and so what remains to figure out is what happens to aof i plus 1 onwards but now my target sum is different because i put a number in my set and so among these items they should sum up to not little t anymore but now little t minus what
i just added which is a i so then if if in this sub problem i get something that sums to t minus a i and then i add a i to that set i will get something that sumsto exactly t and so that's a valid solution to this problem and because we have brute forced all possibilities there were only two uh if we combine these in the suitable way then we will have considered all optionsnow what do we want here so this is normally i'd write max or min but this is a decision problem the output is just yes or no so this is a yes or no answer this is a yesor no answer this is a yes or no answer and so what i want is orin python this would be called any just are any of these things true because if there's any way to construct a set that sums to t then the answer to this is yes cool so very simple actually just
this is one of the simplest recurrences but we're solving what i think is a really impressive problem right we we're asking is there any subset they're exactly two to the n subsets of a here um and we're insome sense considering all two to the n of them but because we split it up into n local choices that are binary and do them only one at a time sort of this is the local brute force versusglobal brute force global brute force would be trial subsets sum them see which ones add up but we're in some sense collapsing a lot of these choices be in reusing sub problems that's the whole point of dynamic programmingwe're looking at uh for the the rest of the of the sequence from i plus one onwards i don't really care exactly which subset you choose i only care what it sums to and that collapses a lot of
different options into the same thing i really just want to know is there any way to do it with exactly this sum so i don't have to think i don't i don't need to keep track if if isaid give me all of the different subsets that sum to t that would be exponential time but because i'm just asking a yes or no question this choice only takes constant time and we get to sum them insteadof product then because we're using memorization that is the beauty of dynamic programming and the this time analysis rule that we only have to sum over sub problems because we only compute each sub problem once so without memoizationthis would take exponential time just like fibonacci with memorization magic i just think this is beautiful so even though it's one of our simpler dps i think it's an impressive one
okay uh topological order well let's look at these function calls so here we have to be a little bit careful when we call x recursively we always increment i but sometimes we don't decrement t sometimes t doesn't godown so if i wrote decreasing t here that would be bad because sometimes i call with the same value of t and i don't want to get into i want to ensure that this has already been computed wheni try to compute this so i is the right thing and we should say decreasing i it doesn't actually matter how we order with respect to t just any order that is decreasing i will be good because thesefunction calls always increase i okay we need a base casebase cases let's see the natural given this aspect i think the natural thing is to have a base case when my suffix is empty which is when i equals n so this is x of uh n comma t
for any little t because we don't have a lot of control of how t is changing but this is easy so this is saying if i give you no numbers what sums can you represent the only sum ican represent is 0.okay so if t equals 0 then the answer is yes and otherwise the answer is noso that's my base case and that's enough and we needed this base case because if we wrote x of n comma t this would try to call x of n plus 1 which doesn't make sense but x ofn call in as a natural suffix which we only allowed i to go up to n and that's the empty suffix so this is enough we need the original problem

9. Chapter 9 (38:07)

uh which is the entire string from zero onwards and capital t for little t that's our target sum and then the running time as i said there are n times t sub problems theta and the amount of workwe spend for each one that isn't recursion is constant we just do a couple subtractions additions do an or and recursive calls so constant time so n times t is the running time of this algorithm let me showyou an example as a subproblem tag really helpful to see how these are hard to draw but they're easy to read i think they're helpful to show what's really going on in this dp this remember every node herecorresponds to a possible subproblem we could have so we have the choices for little t on the top the choices for little i on the left so the original problem we care about is i equals 0 t equals
6.this is the same example that i showed you before where we have three or no it's a different example sorry my new set a is three four three one four numbers here my target value is six this isdefinitely possible i can add three and three this shows that a doesn't have to be sorted we're not assuming anything about the order of a and we're allowed duplicate values and we see indeed there's a y here foryes it is possible and how did i compute that well i just drew a bunch of arrows so there's vertical arrows here always going from each problem to the next one above it because we have this dependency xi of t calls x of i plus 1 comma t so that's the calls are going in this direction so the dependency order is you have to compute things lower down before you compute things up here um and
indeed down here is the base case where we write yes for the first problem and no for all the others because we don't have any numbers we can't represent anything above zero okay and then we have these bluelines i just drew them a different color so they stand out hopefully and they correspond to the numbers here so our first choice is do we include a zero which is three so that's only possible if we're tryingto represent a number uh that's greater than or equal to three which reminds me i forgot to write down in this dp i need to say this option is only an option if a i is less than orequal to t just move my comments here those are the same so this notation means i put this item in this set that we take an or of only if this condition holds okay otherwise i admit it because
it's not a choice why is that important because i don't want to call x on a negative value of t we only are allowed to call x here when t is between zero and capital t so that's subtletybut important for a correct dpso then that's why there's no edge from here for example that goes three to the left because there's no vertex there there's no sub problem so only for uh little t from three onwards we have this edge thatgoes three back and that's just the same pattern over and over then our next number is four and so we have these edges that are go four to the right then our next number is three so we againhave edges that go three to the right and then our next number is one so we have these nice diagonal edges that go one to the right and then what's happening in here at each stage let's take an
interesting one maybe this vertex is we look at each of the incoming neighbors and we take the or so the incoming neighbor here has a no incoming neighbor here has a yes and so we write a yes herewhich means that given just these numbers three and one we can represent the number three namely by taking this edge of weight three sorry of length three and then just going straight down to a base case that's yesthat's representing 0.so in this case we this example i didn't draw the parent pointers here but they're in the notes this yes is possible not from going this way but from going this way so we take the number three thenwe go down which means we skip the number four and then we go left which means we take the number three and then we go down which means we skip the number one okay so we can represent six
as three plus three cool so subset sum not only can we solve the decision problem but by following parent pointers in the yes instances we can actually find a valid subset question you added that condition to the relation

10. Chapter 10 (43:15)

good question um so ins uh it's it's a generally useful technique to add if conditions to the cases to only when they apply you can write a lot of dps that way and that's why i wanted to stressit you could instead of adding this condition allow the case that little t is negative but you have to think about how negative would it be you might say well maybe t between minus big t and plus bigt is enough i don't think so it should be um we're at some value t and we subtract some ai we don't know how the ai's compared to big t probably they're less than or equal to big tbecause they're not useful if they're bigger than big t so you could first prune the ais to guarantee all the ais are less than big t then minus big t to big t would work otherwise it's like minus
the maximum ai up to big t would be enough i think yeah does this restrict to only the positive integers in the input ah do i i am implicitly assuming here that all the ai's are positive uh ithink you can solve it with negative numbers but it's not uh and maybe we'll do it in recitation it is not as it's not a trivial change to this dp i've definitely thought about it before yeah so ishould have said positive integers thank you
cool all right so uh that's subset sum but we come back to this question of is this a good algorithm is it polynomial time so we have this running time n times t so a new question is isn times big t polynomial

11. Chapter 11 (45:08)

and the answer is no why because for this problem what is the input size how many words of input do i have well i have these n integers and then i also have the target sum so similar toup above our input size is n plus one okay but now the labels really matter before it was l plus one and and our running time was a function of l now our input size is just n plusone but our running time is a function of both n and t not polynomial in input size
n plus one you cannot write that n n times capital t is less than or equal to n plus 1 to the 27th power because you just don't know how n and t relate maybe t is at mostn then we're happy but maybe it's not maybe t is 2 to the n why could it be 2 to the n uh because what do we know about capital t we assume implicitly throughout the course the tfits in a word that means it's a w bit number so that means it's at most two to the w and you might think well we know about a relation between w and n so we know t isat most 2 to the w if it's w bitsand we know that our assumption is always that w is at least log n that's the word ram trans-dichotomous assumption but notice we don't know anything about an upper bound on w in order to upper bound t in
terms of n i'd need to say that w is at most log n then this would be at most n and we'd be done but that's not very interesting and generally we allow w to be arbitrarily large withrespect to log n it just has to be at least log n just to be able to index stuff so but w could be really big much bigger than log n for example w equals n is not acrazy idea i mean if if i have a machine that can represent n numbers why not represent n numbers each of which is n bits long and maybe it takes a little more time to compute on those youmight want to scale your running times but it's quite reasonable to think about n-bit numbers and then this is like n times 2 to the n so this would actually be exponential time and if w is 2 to
the n n times t is exponential in the problem size which is n plus 1.and that's just an example w could be bigger okay so this is not what we call a polynomial algorithm or strongly polynomial algorithm but it's still pretty good right as long as we know that capital t is notginormous then this is a great algorithm so it's and we capture that notion with a concept called pseudo-polynomial

12. Chapter 12 (48:24)

it's not the best term but it's the established term it's like polynomial but not quite and the definition of this term so we have the definition of strongly polynomial time uh now uh pseudo-polynomial time this i'll write timehere so you can measure other things pseudopolynomial uh is that we're polynomial uh in the input size just like before
and the input numbers input integers
okay so in this problem the input integers are capital t and a0 a1 up to a n minus 1.so we want now is a polynomial or what some people call a multinomial where our variables are all of these integers and we want to be polynomial in them so we're allowed to take some constant power of capitalt and some constant number of the ais we can't just take the product of all of them that would be bigso it's a i guess i should say constant degree polynomial
and indeed this is a you might call it a quadratic polynomial in the input size and the and one of the numbers so this is this running time is pseudo poly but not poly

13. Chapter 13 (50:06)

and so while normally we think of polynomial time is good exponential time is bad pseudo-polynomial is what we normally call pretty good to be informal
yeah so in particular pseudopolynomial implies polynomial in the special case
so if the input integers
are all at most polynomial
in the input size

14. Chapter 14 (50:50)

this should sound familiar this is a constraint we've seen before this is the condition when radix sort runs in linear time ready sort runs in linear time exactly when all the input integers are polynomially bounded in n whichis the size of the array which is the input size okay so same same condition is appearing again so this is sort of a fundamental setting to think about and let's see so in particular other structures we've seenlike counting sort and direct access arrays are alsopseudopolynomial any others fibonacci sorry rate export yes technically also rate of sort are all uh they're not strongly polynomial but they are pseudo-polynomial uh here we thought about this as a dependence on you which we got rid ofusing hashing but if you just use the order u running time for say build uh that u is is like are bound on the input integers and that's only good when this is polynomial in general it's pseudo-polynomial same
with counting sort we had an order u now we improved this in radix sort to this running time that was uh n times log base n of u plus n if you want to be careful um so orput a ceiling uh now this is a running time that's a little bit better and this is usually called weekly polynomial don't want to spend much time on this but weekly polynomial is just like pseudo-polynomial but instead ofbeing polynomial the input size and the input integers your polynomial in the log of the integers so this is better and it's almost as good as polynomial as strongly polynomial okay we won't really use this notion the onlyplace that appears in this class is in rating sort but future classes you might care about so the the nesting is the best thing you can be is strongly polynomial we just call this polynomial in this class uh
then we have weekly polynomial which is almost as good but you have this logarithmic dependence on the numbers and then the next level is pseudopolynomial this is not as good here this really only works well if the numbersare small logarithmic dependence is pretty good because even if they're exponential this is polynomial sounds funny but log of an exponential is polynomial all right enough about pseudopoly the last thing i want to talk about is reflecting onall of the dynamic programs we've seen so far and characterizing them according to the the big techniques that we used in sort bot the first big technique was how do we define our sub problems did we take prefixesand suffixes or substrings of a sequence did we have multiple sequences and have to take products of those spaces did we have integers and have to take smaller versions of those integers sometimes that leads to pseudo-polynomial algorithms sometimes
not and sometimes we also had sub problems that were defined in terms of vertices this just happened in shortest path problems because that's the only setting where we saw dp over graphs so let me characterize all the dpswe've seen in lecture not the recitation ones for nowin redso for example with the bowling problem with bowling pins we only had to deal with prefixes or suffixes because yeah we were only we could just think about what happened for the first couple of pins for example alsofor lcs we had to take two different sequences but then we just guessed what happened at the in with the first two items of each uh of each sequence and so that only left us with suffixes uh withlongest increasing subsequence again we just guessed whether the first or maybe we assumed that the first item was in the longest increasing subsequence and then we tried to guess what the next item was but that again eliminated everything
in between so we were just left with a suffix this leads me to another characterization of the kind of dynamic programming techniques which is for in addition to these basic sub-problems we often added constraints and expansion and lisis an example of what we call non-expansive constraint where we just added a constraint to the problem which was i'd want this first item to be in my longest increasing subsequence but that didn't actually change the number ofsub-problems so it didn't expand the number of sub problems this is i think the only example we saw with this feature most of the other times when we added a constraint we also increased the number of sub problemswhich we'll get to okay also in a certain sense there's multiple ways to think about this one floyd warshall is a problem or we define subproblems based on prefixes of the vertices right we had vertices 1 through n
we said is their shortest path using vertices just 1 to i so that's a prefix of the vertex set in a particular order so you can think of floyd warshall as being as involving a prefix you can alsothink of it as you're given an integer i and you're only allowed to use vertices less than or equal to i and so it's also kind of an integer sub problem but i will leave it up there alsothe two examples we saw today rod cutting kind of uh you could think of it as either a prefix on the values or i would prefer to think of it down herewhere we had an integer and we were considering smaller integers also and but subset sum definitely had a suffix in addition to having an integer subproblem so rod cutting you can put down here because we looked at smaller
integers or up here but subset sum really is up here and down here because we both looked at suffixes and smaller values of t okay uh fibonacci also fits down here fibonacci was another case where we had anumber n and we looked at integers smaller than n ah good i think i've done these now what problems involve substrings we saw two of them one was the alternating coin game because we were taking from left orright and so we had to look at substrings in between and the other is parenthesization where we had to guess something in the middle and that left the prefix before it and the suffix after both of those aretypical ways where you get substring problems uh okay so pseudo poly both of these are pseudo poly and those those are the ones that we've seen that are dynamic programs pseudopoly and then with vertices it's all the shortest
path uh problems where we also had a parameter which was a vertex these are natural because in the goal of sort of single short shortest paths is distance to each vertex and so naturally we had a sub problemfor each vertex for dag shortest paths for bellman ford and for floyd warshall okay back to subproblem expansion we saw a couple of examples alternating coin game and parenthesization sorry not parenthesization uh yeah parenthesization sorry arithmetic parenthesization sohere we consider two different versions of each subproblem one where i go first and one where you go first and that was really handy though not necessary for parenthesization it turned out we needed both min and max inorder to solve max so we really only cared about max so we doubled the number of sub problems to make it solvable for uh piano and guitar fingering we increase the number of sub problems by a constant or
f or some f to the f or some uh for five fingers this is a reasonable constant um for some amount of state that we wanted to keep track of of the past and one example where we hadlinear expansion sort of is bellman ford so here we were expanding by how many edges are in the shortest path so we really only cared about finding shortest paths we said oh what about at most eye edges soyou can think of that as adding a constraint and then there's n different variations of this these sub problems which leads to expansion what you could also think of it as just adding a single constraint which is icare about the number of edges and that input is an integer and then we're looking at the natural subproblem for integers which is we care about up to length n minus 1 and now let's consider all lengths smaller
than n minus 1.okay and finally the other main feature we had is in the recurrence relation and all these shortest path tags how many incoming edges did we have how many different branches did we have to consider and then uh combinein some way so we saw a lot of examples with constant branching fibonacci where we just was the obvious two-way branching bowling where we had a couple of choices at the beginning lcs longest common subsequence where we hada couple choices what to do at the beginning alternating coin game similarly do we take from the left or the right so just two choices floyd warshall there's two choices do we use that vertex or not subset sumdo we include this item in the subset or not okay so that was all constant branching in a lot of the graph problems we got ordered degree branching which leads to an order e term in the final running

15. Chapter 15 (61:05)

time namely dag shortest paths and bellman ford and then a lot of examples had linear branching um in particular longest increasing subsequence where we didn't know what the next increasing item was so there are n possible choices forit parenthesization where we had to choose anybody in the middle as the last operator and rod cutting that we saw today we could cut the first rod we cut could be any length and then finally once you've consideredall recursed on all these sub problems you have to combine them somehow and in a lot of the problems we actually just take one the one best choice and that is our final solution and in those problems thefinal solution ends up being finding some kind of shortest path in a dag but there are a few cases where we actually took multiple solutions and combined them together to get the overall solution and this includes fibonacci which
is we added them not too interesting floyd warshall we concatenated two paths and parenthesization is maybe the most interesting where we had to take two parts the prefix and the suffix how to solve them and then multiply oradd them together and so these problems are not well represented by shortest path and a dag still a dag involved but it's like a multi-path thing and then finally at the original problem often it's just a single sub-problemis the original problem and there are a few examples namely dag shortest paths and longest increasing subsequence and bellman ford and floyd warshall these were the order that we covered them so the the three shortest paths and thenlongest increasing subsequence where uh here because we added this condition we had to try all the possible choices for this condition i think uh do we also have one here today no okay um so in fact in retrospect
or i mean this we knew this from the beginning but for you in retrospect these four dp lectures were all about showing you these main techniques of dynamic programming from how to set up simple sub problems to differenttypes of basic sub problems to constraining or expanding those sub problems and having initially very simple branching and then getting to bigger branching and different kinds of combination we wanted to show you all these ideas in some orderand if you look back at the sequence that we covered problems we're kind of slowly adding these different main techniques to dp and that's why we chose the examples we did there of course many more examples of dpvery powerful technique but that's the

16. Chapter 16 (63:42)

end you
Seek backward 5s ←
Longer seek (10s) Shift ←
Play Space Seek forward 5s →
Longer seek (10s) Shift →
0:00 Auto-scroll A Copy link at current time S

18. Dynamic Programming, Part 4: Rods, Subset Sum, Pseudopolynomial