Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- /*
- ******IMPORTANT
- SMELL TEST FOR INTERVAL DP
- If ALL the ELEMENTS have to be used, just the ORDER in which they are used matters. (my permutation thinking)
- Connecting it to intervals =>
- If ALL the ELEMENTS in an open interval(i, j) have to be used, just the ORDER in which they are used matters.
- What's the BEST that we can in open interval(i, j), if We are going to use each and every element in the open interval(i, j), just the order in which they are used is CHANGED.
- In OPTIMIZATION(longest, shortest, size, sum etc) problems when we use Index based traversal/mask based traversal to generate subsequence/subset, the potent ANSWERS were varying because some ELEMENTS from the array were chosen and some were not. Each subsequence created(2^N paths) is unique from each other because some different combination of elements were chosen. It is also sometimes bounded by some properties such as size of subsequence should be at max k, or sum of subsequence should be at max k, which allows some of the elements in array to get chosen and we skip some to avoid violating the constraints on the question as specified above. This leads to different subset generation, as different elements were picked from the original Array, and we find the BEST of these subsets.
- BUT in INTERVAL DP optimization problems, ALL the elements of the array have to used/handled, in the open interval(i, j). Our final answer to the optimization question is also defined the same way but the range is the whole array. So What is the BEST we could do in OPEN INTERVAL(0, n + 2), given we have to USE ALL the elements in the open interval(0, n + 2) of the paddedArray, i.e. using elements from indices (0 - N - 1) in the original array.
- It leads to a very IMPORTANT QUESTION...how is the answer(min cost, max profit) varying across different potent answers generated in I-DP problems, if in every POTENT answers ALL the elements are getting used everytime, so a thing like sum of subseqence would always be same, or size of subset would always be same if all elements getting picked...
- ****BUT THE ANSWER HERE VARIES NOT BY CHOOSING/USING/HANDLING/BURSTING/PROCESSING WHICH ELEMENT, BUT WHAT ORDER THE ELEMENTS ARE CHOSEN/USED/HANDLED/BURST/PROCESSED, because every element is going to be used anyways. Every element of the array is being used, but the answer is varying just because how the elements were used in that open interval(i, j).
- AND if you think about it, that is what we are doing through the algorithm=>(handle/burst k last in open interval(i,j))
- For any interval(i, j) if all the elements are used, how the answer will vary? => THROUGH ORDER
- What we are doing => For all k in open interval(i, j), what is the best we could do if all the elements have to used in the interval and we use/handle/burst k AT LAST.
- So for EVERY ELEMENT IN THAT RANGE, we use each element(k) LAST, making sure other elements in that range are getting used BEFORE it. We do this for every element in that range, which generates ALL THE DIFFERENT ORDER in which ELEMENTS CAN BE USED IN THAT INTERVAL.
- AND the CODE recurses on the left and right sub intervals (signifying the elements in those sub intervals were processed earlier than kth element and we have already calculated those sub intervals before) at the level of current open interval(i, j). THIS GENERATES ALL THE POSSIBLE ORDERING OF ELEMENTS IN THAT OPEN INTERVAL(i, j), AND WE CHOOSE THE ORDER THAT DOES THE BEST IN THAT INTERVAL.
- IF you really break it down to the case where interval is something like (2, 5), where only 2 elements are considered{2, 3} as 2 & 5 are EXCLUSIVE. We LOOP over element in the range(2, 5), choose each element as k that is to be handled last, which makes other elements in that range processed first. So for k = 3, we process 3 after 4, and then we choose k = 4, which means we processed 3 earlier. Now We choose when we did the best in the range(2, 5), when we processed 3 at last(k = 3) or 4 at last(k = 4).
- THIS GENERATES THE DIFFERENT ORDERING AT THE LOWEST POSSIBLE STATE as we go higher, OTHER ORDERINGS ARE GENERATED TOO.
- SO basically when we consider any range like range(1,99) or range(8, 88), What we are ESSENTIALLY DOING IS GENERATING ALL THE DIFFERENT ORDER IN WHICH ALL ELEMENTS CAN GET PROCESSED IN THAT INTERVAL, AND CHOOSE THE ANSWER CORRESPONDING TO THE BEST ORDER. BUT FOR EVERY INTERVAL WE DO SO ONCE, AND THERE COULD BE AT MAX(N^2 intervals/subarrays of an Array), SO THERE COULD ONLY BE N^2 state/level computations at max. THAT's WHY WE MEMOISE (i, j) as memo keys, as they are SUFFICIENT TO DEFINE an interval, and we store what is the BEST THAT WE COULD DO in that INTERVAL by processing ALL elements in EVERY possible ORDER.
- So like
- OPEN INTERVAL(i, j) => Use ALL the elements but in DIFFERENT ORDER to form ALL the POTENT ANSWERS TO THAT INTERVAL.
- BY LOOPING, WE TRY DIFFERENT ORDER (by fixing k to be PROCESSED LAST) & CHOOSE THE ANSWER CORRESPONDING TO THE ORDER THAT DID THE BEST IN THAT OPEN INTERVAL(i, j), i.e. That ONE PARTICULAR ORDER of PROCESSING ALL the elements in that open INTERVAL(i, j) which led to MAX PROFIT/MIN COST in that open INTERVAL(i, j).
- AWESOME NICE>>>> FEELS LIKE PERMUTATION ONLY, JUST A BETTER WAY TO GENERATE IT than N! factorial complexity(hard to memoise permutation because each is unique), BUT MEMOISING INTERVAL IS EASY.
- */
- /*
- LOGIC
- For all k in range(i, j)/open interval(i, j), where i & j are exclusive, what is the maximum coins that we can get, if 'kth' balloon is to be burst LAST in open interval(i, j).
- What is the condition which makes 'kth' balloon the last balloon in open interval(i, j)?
- It can only happen when all the balloons to the left of k upto some i, excluding i and all the balloons to right of k upto some j, excluding j are already burst, which leaves only the kth balloon in interval(i, j).
- So if the original subarray is like [1, 2, 4, 6, 8, 10, 1], range(i, j) = range(0, 4)
- and if we consider i = 0, and j = 7, so 0 < k < 7
- and for some k, take k = 2
- The recursive definition would be like => If the 2nd indexed balloon is burst LAST in OPEN interval(0, 7) where 0 & 7 are exclusive, what is the MAXIMUM AMOUNT OF COINS THAT WE CAN MAKE OVER THIS SUBARRAY(0, 7).
- So 2nd index balloon will be the only balloon that is left in OPEN interval(0, 7) as it is the last balloon that is getting burst, which means all the OTHER BALLOONS in OPEN interval(0, 7) are already burst and we have the answer to those range already by recursive defintion.
- So the subarray [1, 2, 4, 6, 8, 10, 1] at k = 2, would look something like:
- (1 [✘ 4 ✘ ✘ ✘] 1)
- where balloons with coins 2, 6, 8, 10 are already burst, and the last remaining balloon in open interval(0, 7) is 4.
- The balloons at index 0 and 7 are not popped/burst because those indices are exclusive in nature. So we select k(balloon to be burst last in interval(i, j)) in between i & j.
- This GUARANTEES, no matter what 'k' in OPEN interval(i, j) is being selected to be burst last, the left neighbour of k will always be the ith indexed balloon and right neighbour will be the jth indexed balloon, as seen in
- (1 [✘ 4 ✘ ✘ ✘] 1)
- So, if the 2nd index balloon is burst last, which means all the balloons in left vicinity and the right vicintiy are already burst and we will have the answer to that.
- leftHalf(i, k) and rightHalf(k, j), as indices are exclusive, so i, j, k are still exclusive and k is also excluded as we are going to pop kth index at the current level/state.
- And popping kth index balloon, we get coins = balloons[k - 1]*balloons[k]*balloons[k + 1].
- BEAUTIFUL DEDUCTION INCOMING!!!!
- As per our definition, kth balloon is the only remaining balloon in interval(i, j) where i & j are EXCLUSIVE, so any kth balloon in range(i, j) will ALWAYS be LEFT BOUNDED BY 'i'th index balloon and RIGHT BOUNDED BY 'j'th index balloon as all the other balloons to left and right of k is already popped except i and j.
- (k - 1) is always i
- (k + 1) is always j
- So popping kth balloon, coinsFromBurstingK = balloons[i]*balloons[k]*balloons[j] and we got this in O(1) time for ANY 'k' IN ANY open interval(i, j).
- So totalCoins in open internval(i, j), if kth balloon is burst last =
- totalCoins = leftHalf + balloons[i]*balloons[k]*balloons[j] + rightHalf;
- We do this for ALL k in open interval(i, j), keep track of max(update maxCoinsInRangeIJ) for each k in (i, j) and the assign the maximum of this to the range(i, j) which is maxCoinsInRangeIJ = memo[i][j].
- Basically what it tells is, for any subarray with range(i, j) / open interval(i, j), the BEST we could do is maxCoinsInRangeIJ. This becomes our OVERLAPPING SUBPROBLEM, as we have already figured out what is the best we could do in this range, we simply return value instead of recalculating.
- */
- int burstballoons3(int i, int j, vector<int> &balloons, vector<vector<int> > &memo){
- //*******IMPORTANT
- //BASE CASE IS REQUIRED BUT IT IS HANDLED IN THE LOOP IMPLICITLY
- //READ EXPLANATION BELOW, but base case is (i + 1 >= j), for this range, max coins made = 0, as the loop won't run, as there are no balloons in exclusive range(i, j)
- //memo check(If already SOLVED for some interval(i, j), return the max coins made in that interval)
- if(memo[i][j] != -1){
- return memo[i][j];
- }
- //for all k in range (i, j) where i & j are exclusive denoted by () => exclusive, [] => inclusive
- //for all k in open interval(i, j); i < k < j
- //so k lies between i & j => i + 1 <= k <= j - 1
- //So for every k to be burst last in the exclusive range(i, j), keep track of the max coins that we get for each k
- //At the end{processed all K in range(i, j)}, WE GET THE MAXIMUM AMOUNT OF COINS THAT WE CAN GET in open interval(i, j)
- //And this is the OVERLAPPING SUBPROBLEM here =>
- // IN RANGE(i, j), what is the MAXIMUM coins that we can get by burst each kth balloon last in open interval(i,j)
- int maxCoinsInRangeIJ = 0;
- for(int k = i + 1; k < j; k++){
- // As kth balloon is to be burst last, the only remaining balloon in open interval(i, j) is k
- //Which ensures that the immediate left neighbour of 'k' is always 'i' & and the immediate right neighbour of 'k' is always 'j', as all the balloons in the open interval(i, j) {balloons between i & j, excluding i & j} has already been burst, making 'k' as the last balloon to be burst in range(i, j)
- int leftHalf = 0, rightHalf = 0, coinsFromBurstingK;
- //Balloons to left of k(excluding k, because it is being burst right now) upto some i(excluding i) already burst, collect the max coins from there
- // We can simply pass i and k, as these bounds are exclusive which means processing will happen between (i and k), i.e. [i + 1, k - 1]
- leftHalf = burstballoons3(i, k, balloons, memo);
- //Balloons to the right of k(excluding k) upto some j(excluding j) are already burst, so collect the max coins from there
- rightHalf = burstballoons3(k, j, balloons, memo);
- //Kth balloon to be burst LAST in open interval(i, j)
- //As all the balloons in the open interval(i, j) are burst except k, that makes 'i' as the immediate left neighbour of k and 'j' as the immediate right neighbour of k.
- // (i ✘ ✘ ✘ ✘ k ✘ ✘ ✘ ✘ ✘ j)
- //For K to be burst last, all balloons to left & right of k is already burst.
- //Which makes i and j the evertime neighbours of any k that is being HANDLED LAST & LIE in EXCLUSIVE range(i, j)
- coinsFromBurstingK = balloons[i]* balloons[k]*balloons[j];
- maxCoinsInRangeIJ = max(maxCoinsInRangeIJ, coinsFromBurstingK + leftHalf + rightHalf);
- }
- //Max amount of coins that we can make in an open interval(i, j)
- return memo[i][j] = maxCoinsInRangeIJ;
- }
- int main() {
- // your code goes here
- int n;
- cin >> n;
- vector<int> balloons(n);
- for(int i = 0; i < n; i++){
- cin >> balloons[i];
- }
- //PAD the original array from the left and right side
- /*
- How would we ensure that all the balloons are being burst(N balloons), as in top down we will start our range as (0, n - 1) AND at every recursive state we CALCULATE
- What is the MAXIMUM COINS that we can get if we burst some kth balloon last in EXCLUSIVE range(0, n - 1). Won't this exclude 0th balloon and (N - 1) th balloon
- */
- //So if we took the original array of size 4 and pass the indices (0, 3)... so it will calculate the maximum coins that we can get in the EXCLUSIVE range of (0, 3) which will exclude the balloon at index 0 and index 3.
- // So pad the array with 1 on each side such that all the balloons are considered in range. so padded array would look like [1, {balloons}, 1]
- //padded Array
- vector<int> paddedBalloons;
- //PAD left side
- paddedBalloons.push_back(1);
- //insert all elements of original array in the new padded array
- paddedBalloons.insert(paddedBalloons.end(), balloons.begin(), balloons.end());
- //PAD right side
- paddedBalloons.push_back(1);
- //The only params changing in the recursive code are i & j
- //Following the 3 step framework to figure the memo key
- //1) CHANGING => They change with each recursive state
- //2) INFLUENCING THE BASE CASE DECISION OR DIRECTLY INVOLVED IN TRANSITION LOGIC OR HELPING US WRITE A CONDITIONAL => for any k in range(i, j), we make recursive call to the LEFT of k and to RIGHT of K, which directly involves i and j in the transition logic itself(which will inturn affect what result we get from the call
- //HERE we don't have any base case, because loop already takes care of it.
- //Generally when we have a base case, we see what variables are influencing the base case decision
- //For example, k partition (not necessarily all equal)
- //index >= nums.size(helps in checking if all elements are processed)
- //k == 0, helps in checking if all k groups are formed
- //IF both conditions met, return 1(valid answer)
- //ELSE return 0
- //HERE both variables are directly influencing on what to return from base case.
- //GENERALLY we don't treat loop variables as a VALID INFLUENCING VARIABLES(if there is any loop involved in the recursive state, such as k partitions) IF BASE CASE IS PRESENT SEPARATELY IN EACH RECURSIVE STATE. Then the loop just help DRIVE recursion FORWARD, and MUST be treated as RECURSIVE SCAFFOLDING instead of POTENT MEMO KEYS. So the QUESTION is why are we treating i & j as memo keys if they are MERE part of loop.
- //IN INTERVAL DP, there is NO REQUIREMENT OF BASE CASE in the version of the code I have written as everything is handled BY THE LOOP.
- //*********IMPORTANT
- //But as we know, we can't recurse without base case, so how are we doing it here => with the help of LOOP ONLY
- //THE BASE CASE IS IMPLICIT here. If we analyse the code, as the loop for k starts from i + 1 and goes till j - 1, so where ever i + 1 >= j, we SIMPLY RETURN 0, as the loop WON'T run even ONCE, and the variable maxCoinsInRangeIJ = 0.
- //So we are actually MAKING USE of this condition (i + 1 >= j) at base recursive state to return 0, which means there are no balloons in exlcusive range(i, j), but it is not EXPLICITLY written in the code.
- //As i & j are being used in the base case/INFLUENCING the decision making in base case,i & j are potent memo keys which are CHANGING & INFLUENCING.
- //The only thing we need to check is if they are DERIVABLE from other parameters.
- // As they are indices, such as index in INDEX BASED TRAVERSAL that I do in level - options method, they are simply not DERIVABLE from other params or from each other.
- //Which makes both of them as the memo keys of this recursive code
- // THEY ARE CHANGING, INFLUENCING AND NOT DERIVABLE , the definition of a MEMO/DP KEY
- //Now we made sure that i & j are the memo keys, we need to figure out the range of i & j
- //i and j are the indices of the paddedBalloons array (REMEMBER THEY ARE NOT THE INDICES OF THE ORIGINAL ARRAY)
- // We use the PADDED ARRAY everytime for solving INTERVAL DP problems such that every element in the original array is INCLUDED.
- //So i & j can go upto paddedBalloons.size()
- vector<vector<int> > memo(paddedBalloons.size(), vector<int>(paddedBalloons.size(), -1));
- //update range to (0, paddedBalloons.size() - 1) instead of (0, n - 1)
- cout << burstballoons3(0, paddedBalloons.size() - 1, paddedBalloons, memo) << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment