[Note]: DP (Dynamic programming)

Source: Internet
Author: User
Tags cmath advantage

First, the basic concept

The dynamic planning process is that each decision relies on the current state and then causes the state to shift. A decision sequence is generated in the state of change, so the process of solving the problem by this multistage optimization decision is called dynamic programming.

Second, basic ideas and strategies

The basic idea is similar to the divide-and-conquer method, and the problem to be solved is decomposed into several sub-problems (stages), and the solution of the sub-stage is solved in order, which provides useful information for the solution of the latter sub-problem. When solving any sub-problem, the various possible local solutions are listed, and the local solutions that are likely to achieve the best are preserved by decision, and other local solutions are discarded. Solve each sub-problem in turn, the last sub-problem is the solution of the initial problem.

Because the problem of dynamic planning solves most overlapping sub-problems, in order to reduce the repetition, we only solve each sub-problem once and save the different states of different stages in a two-dimensional array.

The biggest difference between the division and the method is: suitable for the problem solved by the dynamic programming method, the sub-problems obtained after decomposition are often not independent of each other (that is, the next sub-stage solution is based on the solution of the previous sub-stage, and further solution).

Third, the application of the situation

There are 3 properties that can be used to solve the problem of dynamic programming:

(1) Optimization principle: If the optimal solution of the problem contains sub-problem solution is also optimal, it is said that the problem has the optimal sub-structure, that is, to meet the optimization principle.

(2) No effect: that is, once a stage state is determined, it is not affected by the decision after this state. In other words, the subsequent process of a State does not affect the previous state, only the current state.

(3) There are overlapping sub-problems: That is, sub-problems are not independent, a sub-problem in the next stage of decision-making may be used more than once. (This nature is not a necessary condition for dynamic programming, but without this nature, the dynamic programming algorithm has no advantage over other algorithms)

Iv. Basic steps of the solution

The problem that dynamic programming deals with is a multi-stage decision-making problem, which usually starts from the initial state and reaches the end state through the choice of the intermediate stage decision. These decisions form a sequence of decisions, while defining an active route (usually the optimal activity route) to complete the process. As shown in the figure. The design of dynamic planning has a certain pattern, which usually goes through the following steps.

Initial state →│ decision 1│→│ decision 2│→ ... →│ decision n│→ End State

Fig. 1 schematic diagram of dynamic planning decision process

(1) Division stage: According to the question Time or the space characteristic, divides the question into several stages. In the partitioning phase, note that after the division of the stage must be ordered or sortable, otherwise the problem can not be solved.

(2) Determining state and state variables: the various objective situations in which the problem is developed into various stages are expressed in different states. Of course, the choice of state to meet no-no validity.

(3) Determine the decision and write out the state transition equation: Because decision-making and state transfer have a natural connection, state transfer is to export the state of this stage according to the state and decision of the previous stage. So if the decision is made, the state transfer equation can be written out. In fact, it is often done in turn to determine the decision-making method and the state transition equation based on the relationship between the states of the adjacent two phases.

(4) Finding the boundary condition: the given State transfer equation is a recursive type, which requires a recursive terminating condition or boundary condition.

In general, the state transition equation (including boundary conditions) can be written as long as the phase, State and state transfer decisions of the problem are resolved.

Practical applications can be designed in a few simplified steps, as follows:

(1) Analyzing the properties of the optimal solution and characterizing its structural characteristics.

(2) A recursive definition of the optimal solution.

(3) Calculate the optimal value from the bottom-up or top-down memory (Memo method)

(4) According to the information obtained when calculating the optimal value, the optimal solution of the structural problem

Five, the implementation of the description of the algorithm

The main difficulty of dynamic programming is the theoretical design, that is, the above 4 steps to determine, once the design is complete, the implementation of the part will be very simple.

Using dynamic programming to solve problems, the most important thing is to determine the three elements of dynamic planning:

(1) phase of the problem (2) status of each stage

(3) The recurrence relationship between the previous phase and the latter one.

The recursive relationship must be from the minor problem to the transformation between the larger problem, from this point of view, dynamic planning can often be implemented with recursive programs, but because recursion can take full advantage of the previous saved sub-problem of the solution to reduce duplication, so for large-scale problems, there is a recursive incomparable advantage, This is also at the heart of the dynamic programming algorithm.

The three elements of dynamic programming are determined, the whole process can be described by an optimal decision table, the optimal decision table is a two-dimensional table, where the row represents the stage of decision-making, the column represents the state of the problem, the table needs to fill in the data generally corresponding to the problem at some stage of a state of the optimal value (such , maximum value, etc.), the process of filling in the form is based on the recurrence of the relationship, starting from 1 rows and 1 columns, in the order of row or column priority, fill in the table, and finally according to the entire table data through simple trade-offs or calculations to obtain the optimal solution of the problem.

F (n,m) =max{f (N-1,m), F (N-1,m-w[n]) +p (n,m)} above for reprint transfer

The following is a simple dynamic planning template


1. Longest ascent subsequence Lis

A. General practice

Time complexity O (n^2) 
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 10000//This procedure n cannot be too large 
using namespace Std;
int main () {
	int n;
	int a[n],f[n],mx,ans=0;
	scanf ("%d", &n);
	for (int i=1;i<=n;i++)
		scanf ("%d", &a[i]);
	for (int i=1;i<=n;i++) f[i]=1;
	for (int i=1;i<=n;i++)
	{
		mx=0;
		for (int j=1;j<=i-1;j++)
			if (F[j]>mx&&a[j]<a[i])//change to <= is not the descent subsequence 
			{
				mx=f[j];f[i]= f[j]+1;
			}
	}
	for (int i=1;i<=n;i++)
		Ans=max (Ans,f[i]);
	printf ("%d", ans);
	return 0;
}
Optimization of B.lic

It's a waste of time to start a 1 to I-1 cycle. Open a G array to save the current optimal maximum ascending sequence

The time complexity is reduced to the NLOGN level with the Lower_bound function (lower_bound similar to binary lookup) 
//More with improved version without common practice Low_bound (begin,end,val) Returns the address of the first element that inserts Val to make a sequence or an ordered sequence minus the begin address is his array ordinal-1 (array starting from 1) 
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath >
#define INF 0x7fffffff
#define N 5000000
using namespace std;
The int n,a[n],f[n],g[n],ans;//g array saves a longest ascending ordered sequence 
int main () {
	scanf ("%d", &n);
	for (int i=1;i<=n;i++) scanf ("%d", &a[i]);
	for (int i=1;i<=n;i++) {g[i]=inf;f[i]=1;}
	for (int i=1;i<=n;i++) {//backwards from N to 1 loops is the longest descending subsequence 
		int k=lower_bound (G+1,g+1+n,a[i])-(g+1);//Must be reduced (g+1) at this time k= The previous position of the insertion position because the array starts at 1 
		g[k+1]=a[i];
		f[i]=k+1; 
		/* can be written as such 
			int k=lower_bound (G+1,g+1+n,a[i])-(g);
			G[k]=a[i];
			f[i]=k; 	
		*/
	} for
	(int i=1;i<=n;i++)
		Ans=max (Ans,f[i]);
	printf ("%d", ans);
	return 0;

Simple DP Exercises

1. Chorus formation

https://vijos.org/p/1098
//Seek one longest ascent one longest drop then F1[i]+f2[i] The biggest is the best middle position answer for f1[i]+f2[i]-1 (minus yourself) 
#include < iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#define INF 0x7fffffff
#define N 5000000
using namespace std ;
int n,a[n],f1[n],g1[n],ans,f2[n],g2[n],mx=0;
int main () {
	scanf ("%d", &n);
	for (int i=1;i<=n;i++) scanf ("%d", &a[i]);
	for (int i=1;i<=n;i++) {g1[i]=inf;g2[i]=inf;f1[i]=1;f2[i]=1;}
	for (int i=1;i<=n;i++) { 
		int k=lower_bound (G1+1,g1+1+n,a[i])-(g1+1);
		G1[k+1]=a[i];
		f1[i]=k+1; 
	}
	for (int i=n;i>=1;i--) { 
		int k=lower_bound (G2+1,g2+1+n,a[i])-(g2+1);
		G2[k+1]=a[i];
		f2[i]=k+1;
	}
	for (int i=1;i<=n;i++) {
		if (f1[i]+f2[i]-1>mx) mx=f1[i]+f2[i]-1;
	} 
	printf ("%d", n-mx);
	return 0;

2.codevs1620 Ship Problem

http://codevs.cn/problem/1620/
//The first bank is sorted and then the longest ascending subsequence of the other shore is obtained 
#include <iostream>
#include < cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#define INF 0x7fffffff
#define N 5005
using namespace std;
int x,y,n,f[n],g[n],a[n],mx;
struct node{
	int x, y;
} Bank[n];
BOOL CMP (node Xx,node yy) {
	if (XX.Y!=YY.Y) return xx.y<yy.y;
	else return xx.x>yy.x;
	The topic says that no two cities have the same friendly city, but the examples are: So xx.x>yy.x if there are multiple points corresponding to a city will only take the middle one (will not take more than one) 
}
int main () {
	scanf ("%d%d", &x,&y);
	scanf ("%d", &n);
	for (int i=1;i<=n;i++)
		scanf ("%d%d", &bank[i].x,&bank[i].y);
	Sort (bank+1,bank+1+n,cmp);
	for (int i=1;i<=n;i++) {f[i]=1;g[i]=inf;}
	for (int i=1;i<=n;i++) a[i]=bank[i].x;
	for (int i=1;i<=n;i++) {
		int k=lower_bound (G+1,g+1+n,a[i])-(g+1);
		G[k+1]=a[i];
		f[i]=k+1;
	}
	for (int i=1;i<=n;i++)
		Mx=max (Mx,f[i]);
	printf ("%d\n", MX);
	return 0;
}

3. Horse-stopping river crossing vijos1121

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int main ()
{
    int i,j,x,y,n,m,f[100][100];
    Long long ans[100][100];
    scanf ("%d%d%d%d", &n,&m,&x,&y);
    memset (F,1,sizeof (f));
    memset (ans,0,sizeof (ans));
    Ans[0][0]=1;
    f[x][y]=0;f[x+1][y+2]=0;f[x-1][y+2]=0;
    f[x+1][y-2]=0;f[x-1][y-2]=0;f[x+2][y+1]=0;
    f[x-2][y+1]=0;f[x+2][y-1]=0;f[x-2][y-1]=0;
    for (I=1; i<=n; i++)
        if (f[i][0])
            ans[i][0]=1;
        else break;
    for (I=1; i<=m; i++)
        if (F[0][i])
            ans[0][i]=1;
        else break;
    For (I=1, i<=n; i++) for
        (j=1; j<=m; j + +)
            if (F[i][j])
                ans[i][j]=ans[i-1][j]+ans[i][j-1];
    printf ("%lld\n", Ans[n][m]);
    return 0;
}

4. Tree Tower

	 /* 1
	2 3
   4 5 6
  2 4 2 1 
give a tree tower to go down from the vertex to find the maximum weight on the path and
Input
4 1 2
3
4 5 6
2 4 2 1 
Output
*/
#include <iostream>
#include <cstdio>
#include < cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
# Define INF 0x7fffffff
#define N 4000
using namespace std;
int f[n][n],a[n][n],mx;
int main () {
	int n;
	scanf ("%d", &n);
	for (int i=1;i<=n;i++)
		for (int j=1;j<=i;j++)
			scanf ("%d", &a[i][j]);
	for (int. i=1;i<=n;i++) for
		(int j=1;j<=i;j++)
			F[i][j]=max (f[i-1][j],f[i-1][j-1]) +a[i][j];
	for (int i=1;i<=n;i++)
		Mx=max (Mx,f[n][i]);
	printf ("%d", MX);
	return 0;
}




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.