Delete number [DP]

> Description
there are N different positive integers x1, x2, ... xN in a row, we can remove a continuous number i (the number of sides can only be removed) from the left or right, 1 <= i <= n , the remaining number of Ni number, then the rest of the operation according to the above process until all numbers are deleted.
Each operation has a value of operation, for example, now you want to delete all the numbers from i k position to position. Operation value of | xi - xk | * (k -i + 1), if only remove a number, the value of the value of the operation number.
Task
how you can get the maximum value, the maximum value of the find operation.


> Input
first line a positive integer N, there is a second row separated by a space of N different positive integer number N.

> Output
contains a positive integer, the maximum value for the operation


>Sample Input
6
54 29 196 21 133 118

>Sample Output
768

Described, can be obtained through three times the maximum operation, first remove the front 54,29,196 number 3, the operation value of 426. The second operation is to remove the last digit in the number of the remaining 118 (21 133 118) three, the value of 118 operations. A third operation to remove the remaining number of 2 133 and 21, the operation value of 224. The total value of the operation 426 + 118 + 224 = 768.

Constraints and tips
. 3 <= N <= 100
N operand is an integer between 1 ... 1000.


> Problem-solving ideas
DP to do.
See it as long as two consecutive like numbers, a bit like a stone merge, as long as the combined length of the enumeration sequence, the start position (end position), the position of the boundary.


> Code

#include<iostream>
#include<cstdio>
using namespace std;
int n,a[105],f[105][105]; //f[i][j]表示从i~j的最大价值
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	 scanf("%d",&a[i]),f[i][i]=a[i]; //初始值
	for(int k=2;k<=n;k++)
	 for(int i=1;i<=n-k+1;i++)
	 {
	 	int j=i+k-1;
	 	f[i][j]=max(a[i]-a[j],a[j]-a[i])*(j-i+1); //从i~j整个一起去掉
	 	for(int t=i;t<j;t++)
	 	 f[i][j]=max(f[i][j],f[i][t]+f[t+1][j]); //分两块去掉
	 }
	printf("%d",f[1][n]);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43010386/article/details/90925601