Solving the scrolling array of dynamic programming algorithm (C + +)

Source: Internet
Author: User
Tags lintcode

Although the contact dynamic programming algorithm has been a period of time, to a 01 knapsack problem, can do a simple table rough down, and then to obtain the results, but the mind always feel that the algorithm is not in place, holding the love of the algorithm, many online Daniel's algorithmic thinking really let me admire the pleasantly surprised. In this talk about the dynamic planning of the rolling array solution, is to do a record of this knowledge point, but also want to write the wrong place, we can not hesitate to enlighten.

First, we look at the "scrolling array" example, you can refer to http://www.lintcode.com/en/problem/house-robber/

Test instructions probably said: A thief to steal a series of house property, there are alarms between the house, when and only when two adjacent houses are stolen at the same time will automatically alarm, each house has a certain amount of value, how can thieves do to steal the maximum value of the amount.

The following four points (or four points for dynamic programming topics) should be noted for solving this type of problem:

1. Status (state)

Results for storing small-scale problems

2. equation (function)

An equation introduced by the state, that is, how to launch a large state through a small state

3. Initialization (initialization)

The initial state, as the starting point of the equation

4. Results (Result)

Results based on the state of each step

Back to the House-robber topic, this topic is a typical scrolling array type problem. Given an array, we are not able to take the adjacent two elements, how the extraction can make the obtained results and maximum. For example, given [4,9,1], we can take [4,1] or [9], obviously a result is 5, one result is 9, so the result here should be the latter's extraction. In the State of the establishment, we can understand, with A[n] array to represent each element (subscript starting from 0), when we encounter the first element of the time, we are not taken, when we take the first I-1 element, we can not take, or remove the first I-1 element, To facilitate the acquisition of element I . If we use f[n] to represent the maximum value that can be obtained after we have encountered the nth element, we make the action (taking or not), that is, when we take the first element, we are judging the size of f[i-2] + a[i] and f[i-1], then f[i] = max (f[i-2]+a [I],f[i-1]), do you say yes? We do not have to take care of how the elements before i-3 are taken, because, according to this law, the F[i-2] already contains the largest number of positions available to i-2 elements.

At this point, the above has clarified the "state" of this idea and "equation", leaving "initialization state" and "result", we can notice the result of determining the first equation, we need to use the i-2 element forward, so the No. 0 element and the 11th element need to be initialized content, Because none of these two elements can be pulled out with i-2 elements, there is f[0] = a[0],f[1] = max (a[1],a[0]). The result is the result of our action on the n-1 element, which is stored in f[n-1] .

Implemented by code:

Long LongHouserobber (vector<int>A) {        if(0= = A.size ())return 0; intf[a.size ()]; f[0] = a[0]; if(A.size () >1) f[1] = max (a[0],a[1]);  for(inti =2; I<a.size (); i++) F[i]= A[i] + f[i-2]> f[i-1]? A[i] +f[i-2]:f[i-1]; returnF[a.size ()-1]; }

Thus, the result can be obtained in the time complexity O (n), and the spatial complexity is O (n).

"Here I extend a little, f[i] results are obtained by comparing the results of f[i-2]+a[i] and f[i-1], that actually i-3 and its previous space do not need to be reused, so we can only use three space reuse to represent each State, in order to achieve the space complexity of O (1)"

--------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------

The above is an array of the rolling array algorithm solution process, and then explore the two-dimensional array of rolling array solution process, we can refer to Http://www.lintcode.com/en/problem/maximal-square/

Test instructions: Given a two-dimensional array that contains only 01, find the largest square and make all the elements of this square 1

We use Matrix[n][m] to represent this two-dimensional array, and dp[n][m] represents the longest square edge of the upper-left corner that matches the condition. First, let's make sure four elements. "State" We want to determine how to determine the state of [I,j], push forward a step there are three states, respectively [i-1,j],[i,j-1] and [i-1,j-1], these three states also represent the upper left corner of the largest square, we use the figure to express understanding:

                  

Here in order to facilitate the drawing of dp[i-1][j],dp[i][j-1],dp[i-1][j-1] equal situation, it can be easily seen, when dp[i-1][j],dp[i][j-1],dp[i-1][j-1] equal time dp[i][j] equals dp[ I-1][j],dp[i][j-1],dp[i-1][j-1] One of them plus 1, if dp[i-1][j],dp[i][j-1],dp[i-1][j-1] unequal, that dp[i][j] depends on dp[i-1][j],dp[i][ J-1],dp[i-1][j-1] Among the small one, here lazy is not drawing, we can do their own painting to see, hehe ~. So the "state" is determined, "equation" is also easy to get dp[i][j] = min (dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) +1. The "initialization state" can be thought of starting from [[]] to apply this equation (assuming we are gradually determining the state from [0,0] to [n,m]), so i=0 and j=0 are the things that need to be initialized, in which case dp[i][j] = matrix[i][j]. "Result" is the square max{dp[n][m]}2 of the maximum value in the DP matrix.

Code implementation:

intMaxsquare (vector<vector<int> > &matrix) {        //Write your code here        introw =matrix.size (); intCol = matrix[0].size (); intDp[row][col]; int_max =0;  for(inti =0; i<row;i++) {dp[i][0] = matrix[i][0]; Dp[i][col-1] = matrix[i][col-1]; _max= dp[i][0]|dp[i][col-1]; }         for(inti =0; i<col;i++) {dp[0][i] = matrix[0][i]; Dp[row-1][i] = matrix[row-1][i]; _max= dp[0][i]|dp[row-1][i]; }         for(inti =1; i<row;i++)             for(intj =1; j<col;j++){                if(1= = Matrix[i][j]) dp[i][j] = min3 (dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) +1; ElseDP[I][J] =Matrix[i][j]; _max=Max (Dp[i][j],_max); }        return_max*_max; }

Time complexity O (n*m), Space complexity O (n*m)

"Expansion: Refer to the expansion of an array of ideas, we determine [i,j] state, respectively, using the [i-1,j],[i,j-1],[i-1,j-1] These three states, so we can think of 4 space to repeat the state, but because for the two-dimensional array, This state will be lost when the line is changed (because 4 spaces represent the four states at the end of the line), so we can only use two lines (2*n) to maintain the state "the extended code is given below, for reference only, because the initialization state is written in the traversal process, which can cause confusion, Please understand:

intMaxsquare (vector<vector<int> > &matrix) {        introw =matrix.size (); intCol = matrix[0].size (); intdp[2][col]; int_max =0;  for(inti =0; i<col;i++) dp[0][i] = matrix[0][i];  for(inti =1; i<row;i++)             for(intj=0; j<col;j++){                if(0= = j) dp[1][J] =Matrix[i][j]; Else{                    if(1= = Matrix[i][j]) dp[1][J] = min3 (dp[0][j],dp[1][j-1],dp[0][j-1])+1; Elsedp[1][J] =0; } _max= Max (_max,dp[1][j]); dp[0][j-1] = dp[1][j-1]; } dp[0][col-1] = dp[1][col-1]; return_max*_max; }

This space complexity can be reduced to O (m).

The above is a personal understanding of the process of solving the rolling array, each code has been tested by me to be available, if there is a problem, I hope you put forward treatise.

Respect intellectual property rights, reprint quoted please inform the author and indicate the source!

Solving the scrolling array of dynamic programming algorithm (C + +)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.