zoukankan      html  css  js  c++  java
  • CF1312E Array Shrinking(区间dp)

    Array Shrinking

    思路:可以看出是区间dp的问题,n = 500,刚好可以是O(n^3)。难点在于相邻数字合并的维护,这里我们可以定义一个二维的数组a[l][r],表示L到R区间合并后的数字是a[l][r],比如 3 3 3 a[1][2] = 4, a[2][3] = 4,然后dp[l][r]表示L到R的最短数列长度,容易想到当dp[l][mid-1]和dp[mid][r]等于1且a[l][mid-1] == a[mid][r]时,区间可以合并。可以推出状态转移方程:

    ①(dp[l][mid-1] == 1 && dp[mid][r] == 1 && a[l][mid-1] == a[mid][r]) dp[l][r] = 1, a[l][r] = a[mid][r] + 1;

    ②dp[l][r] = min(dp[l][mid_1 - 1] + dp[mid_1][r], dp[l][mid_2 - 1] + dp[mid_2][r]...);

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <functional>
    #include <set>
    #include <vector>
    #include <queue>
    #include <cstring>
     
    using namespace std;
     
    #define ll long long
    #define pb push_back
    #define fi first
    #define se second
     
    const int N = 2e5 + 10;
    const int INF = 1e9;
    const int MAX_DIS = 2e6;
    
    int _case = 0;
    
    void solve(){
        int n;
        cin >> n;
        vector<vector<int > > num(n + 1, vector<int >(n + 1));
        for(int i = 1; i <= n; ++i) cin >> num[i][i];
        vector<vector<int > > dp(n + 1, vector<int >(n + 1, INF));
        for(int i = 1; i <= n; ++i) dp[i][i] = 1;
        for(int len = 2; len <= n; ++len){
            for(int l = 1; l <= n - len + 1; ++l){
                int r = l + len - 1;
                for(int mid = l + 1; mid <= n; ++mid){
                    if(dp[l][mid - 1] == 1 && dp[mid][r] == 1 && 
                       num[l][mid - 1] == num[mid][r]){
    
                        dp[l][r] = 1;
                        num[l][r] = num[mid][r] + 1;
                    }else{
                        dp[l][r] =
                        min(dp[l][r], dp[l][mid - 1] + dp[mid][r]);
                    }
                }
            }
        }
        //cout << "ans  =";
        cout << dp[1][n] << endl;
    }
    
    int main(){
        
        ios::sync_with_stdio(false);
        cin.tie(0);
        cout.tie(0);
        solve();
        
        return 0;
    }
  • 相关阅读:
    基于perl的网络爬虫
    ios cell展示可滑动的图片
    iOS计算字符串的宽度高度
    swift水波效果
    iOS添加另一个控制器的时候要注意啊
    swift隐藏显示导航栏的底线
    swift集成alamofire的简单封装
    tableview详细介绍
    xmpp xml基本语义
    xmpp SASL 定义
  • 原文地址:https://www.cnblogs.com/SSummerZzz/p/12769499.html
Copyright © 2011-2022 走看看