CodeForces - 1312E Array Shrinking【区间DP】

The meaning of problems

Given the array a 1 , a 2 , . . . , a n a_1, a_2, ...,a_n You can do the following to the array any number of times :

  • Selecting a pair of adjacent and equal in number, a i = a i + 1 a_i = a_{i+1}
  • use a i + 1 a_i+1 instead of the logarithmic

After several arrays now seek operation, the shortest possible length.

1 n 500 , 1 a i 1000 1 \ k \ le500, 1 \ The a_i \ le1000

5
4 3 2 2 3
2

7
3 3 4 4 4 3 3
2

3
1 3 5
3

1
1000
1

answer

  • status: d p [ i ] [ j ] dp[i][j] represents the [i, j] array may reduce the range of the shortest length
  • An array of additional w [ i ] [ j ] w[i][j] indicatesif [i, j] can be shortened to a length in the range of a value of 1, if dp [i] [j] is not one that w [i] [j] does not make sense. The determination for merging two array section
  • State transition: d p [ i ] [ j ] = m i n ( d p [ i ] [ k ] + d p [ k + 1 ] [ j ] ) , k [ i , j ] dp[i][j] = min(dp[i][k] + dp[k+1][j]), k∈[i,j]
  • If there is k such that d p [ i ] [ k ] = = 1 ,   d p [ k + 1 ] [ j ] = = 1 ,   w [ i ] [ k ] = = w [ k + 1 ] [ j ] dp[i][k]==1, \ dp[k+1][j]==1, \ w[i][k]==w[k+1][j] Well d p [ i ] [ j ] = 2 dp[i][j]=2
#include<cstdio>
#include <iostream>
using namespace std;
#define ll long long
#define pr pair<int, int>
const int maxn=4000;

int n, m, ans;

int a[maxn];
int dp[maxn][maxn], val[maxn][maxn];

int main()
{
    cin >> n;
    for(int i=1;i<=n;i++){
        cin >> a[i];
        val[i][i] = a[i]; dp[i][i] = 1;
    }
    for(int i=n-1;i>0;i--)
    {
        for(int j=i+1;j<=n;j++)
        {
            dp[i][j] = 0x3f3f3f3f;
            for(int k=i;k<j;k++)
            {
                if(dp[i][k]+dp[k+1][j] < dp[i][j])
                {
                    dp[i][j] = dp[i][k] + dp[k+1][j];
                    if(val[i][k]==val[k+1][j] && dp[i][k] == dp[k+1][j] && dp[i][k] == 1)
                    {
                        val[i][j] = val[i][k] + 1;
                        dp[i][j] = 1;
                    }
                }
            }
        }
    }
    cout << dp[1][n] << endl;

    return 0;
}
Published 40 original articles · won praise 15 · views 1802

Guess you like

Origin blog.csdn.net/irimsky/article/details/104842428