Interval DP refers to a series of dynamic programming carried out over a period of time. For the problem of interval DP, we need to calculate the answer of interval [1,n], which is usually represented by a two-dimensional array dp, where Dp[x][y] represents the interval [x, y]. Some topics, dp[l][r] are pushed by dp[l][r?1] and Dp[l+1][r], and there are topics where we need to enumerate the intermediate points in the interval [l,r], which can be combined by two sub-problems, or dp[l][r] by dp[l][k] and Dp[k+1][r]. Which L≤k<r. For an interval DP of length n, we can calculate [1,1],[2,2] first ... [N,n] The answer, then calculate [1,2],[2,3] ... [N?1,n], and so on, until you get the answer to the original question.
A classic example:
NOI 1995 Stone merger title description
Placing n heaps of stones around a circular playground is now a sequence of stones to be merged into a pile. The rule is that only the adjacent 2 stacks can be merged into a new pile at a time, and the new pile of stones is counted as the score of that merger.
In this paper, we design 1 algorithms to calculate the minimum score and the maximum score of combining n heap stones into 1 piles.
Input/output format
Input Format:
The 1th line of data is a positive integer n,1≤n≤100, which indicates that there are n heap stones. The 2nd line has n number, which indicates the number of stones per heap.
output Format:
Output total 2 lines, 1th behavior minimum score, 2nd behavior maximum score.
Input/Output sample
Input Sample # #:
44 5 9 4
Sample # # of output:
4354
Analysis
We use the idea of dynamic planning to divide the problem into sub-problems, in order to find the ultimate minimum cost, we only ask for the minimum cost of two heaps, then find the minimum cost of three, and so on to obtain the ultimate minimum cost.
We use DP[I][J] to represent the minimum cost of merging the stones in the I-to-J interval. Then we write the following formula:
Dp[i][j]=min (Dp[i][k]+dp[k+1][j]) +sum[j]?sum[i?1]
Obviously through this equation, we can enumerate the lengths from small to large in order to keep the stones merging, and eventually we can get the minimum cost of merging them into a pile of pebbles.
1#include <bits/stdc++.h>2 using namespacestd;3 Const intMAXN = -+Ten;4 intN, stone[2*MAXN], mi[2*maxn][2*MAXN], mx[2*maxn][2*MAXN], s[2*MAXN];5 intMain ()6 {7CIN >>N;8 for(inti =1; I <= N; i++)9CIN >> Stone[i], stone[i+n] =Stone[i];Ten for(inti =1; I <=2*n; i++) OneS[i] = s[i-1] +Stone[i]; A for(inti =2*n-1; I >=1; i--) - { - for(intj = i+1; J < N+i; J + +) the { -MI[I][J] =0x3f3f3f3f; - for(intK = i; K < J; k++) - { +Mi[i][j] = min (mi[i][j], mi[i][k]+mi[k+1][j]+s[j]-s[i-1]); -MX[I][J] = max (Mx[i][j], mx[i][k]+mx[k+1][j]+s[j]-s[i-1]); + } A } at } - intANS1 =0x3f3f3f3f, Ans2 =0; - for(inti =1; I <= N; i++) -ans1 = min (ans1, mi[i][i+n-1]), ANS2 = Max (ans2,mx[i][i+n-1]); -cout << ans1 << endl << ans2 <<Endl; - return 0; in}
Interval Dynamic Programming