zoukankan      html  css  js  c++  java
  • 区间DP

    区间 DP

    一、定义

    区间 DP,顾名思义是在区间上 DP,它的主要思想就是先在小区间进行 DP 得到最优解,然后再利用小区间的最优解合并求大区间的最优解。

    二、实现思路

    下面给出区间 DP 最简单形式的伪代码 (具体要根据题目修改)

    //mst(dp,0) 初始化DP数组
    for(int i=1;i<=n;i++)
    {
        dp[i][i]=初始值
    }
    for(int len=2;len<=n;len++)  //区间长度
    for(int i=1;i<=n;i++)        //枚举起点
    {
        int j=i+len-1;           //区间终点
        if(j>n) break;           //越界结束
        for(int k=i;k<j;k++)     //枚举分割点,构造状态转移方程
        {
            dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]+w[i][j]);
        }
    }
    View Code

    三、经典例题

    1. 石子合并问题

    石子合并(一) 

    有 N 堆石子排成一排,每堆石子有一定的数量。现要将 N 堆石子并成为一堆。合并的过程只能每次将相邻的两堆石子堆成一堆,每次合并花费的代价为这两堆石子的和,经过 N-1 次合并后成为一堆。求出总的代价最小值。

    输入

    有多组测试数据,输入到文件结束。每组测试数据第一行有一个整数 n,表示有 n 堆石子。接下来的一行有 n(0< n <200)个数,分别表示这 n 堆石子的数目,用空格隔开

    输出

    输出总代价的最小值,占单独的一行

    样例输入:

    3

    1 2 3

    7

    13 7 8 16 21 4 18

    样例输出:

    9

    239

    【思路】

    我们 dp[i][j] 来表示合并第 i 堆到第 j 堆石子的最小代价。那么状态转移方程为:

    dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]+w[i][j]);

    其中 w[i][j] 表示把两部分合并起来的代价,即从第 i 堆到第 j 堆石子个数的和,为了方便查询,我们可以用 sum[i] 表示从第 1 堆到第 i 堆的石子个数和,那么 w[i][j]=sum[j]-sum[i-1].

    #include<bits/stdc++.h>
    using namespace std;
    #define LL long long
    #define fi first
    #define se second
    #define pb(a) push_back(a)
    typedef pair<int,int> pii;
    typedef pair<pii,string> pis;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int MAX_N = 1e3+7;
    int N,M,T,S;
    int dp[MAX_N][MAX_N];
    int vec[MAX_N];
    int sum[MAX_N];
    int main() {
        while(cin>>N){
            memset(dp,0x3f,sizeof(dp));
            for(int i=1;i<=N;i++){
                scanf("%d",&vec[i]);
            }
            sum[0] = 0;
            for(int i=1;i<=N;i++){
                sum[i] = sum[i-1] + vec[i];
            }
            for(int i=0;i<MAX_N;i++){
                dp[i][i] = 0;
            }
            for(int len = 2;len<=N;len++){
                for(int i=1;i<=N;i++){
                    int j = i + len - 1;
                    if(j > N) continue;
                    for(int k=i;k<j;k++){
                        dp[i][j] = min(dp[i][j] , dp[i][k] + dp[k+1][j] + sum[j] - sum[i-1]);
                    }
                }
            }
            cout<<dp[1][N]<<endl;
        }
        return 0;
    }
    View Code

    【平行四边形优化】 

    上面的代码运行时间在 240ms 左右,通过这题完全没问题,但我们还可以考虑优化。

    由于状态转移时是三重循环的,我们想能否把其中一层优化呢?尤其是枚举分割点的那个,显然我们用了大量的时间去寻找这个最优分割点,所以我们考虑把这个点找到后保存下来

    用 s[i][j]表示区间 [i,j] 中的最优分割点,那么第三重循环可以从 [i,j-1) 优化到【s[i][j-1],s[i+1][j]】。(这个时候小区间 s[i][j-1]和 s[i+1][j]的值已经求出来了,然后通过这个循环又可以得到 s[i][j]的值)。

    关于平行四边形优化的证明可以参考这篇博客:可耐的链接QAQ

    #include<bits/stdc++.h>
    using namespace std;
    #define LL long long
    #define fi first
    #define se second
    #define pb(a) push_back(a)
    typedef pair<int,int> pii;
    typedef pair<pii,string> pis;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int MAX_N = 1e3+7;
    int N,M,T,S;
    int dp[MAX_N][MAX_N];
    int vec[MAX_N];
    int sum[MAX_N];
    int s[MAX_N][MAX_N];
    int main() {
        while(cin>>N){
            memset(dp,0x3f,sizeof(dp));
            for(int i=1;i<=N;i++){
                scanf("%d",&vec[i]);
            }
            sum[0] = 0;
            for(int i=1;i<=N;i++){
                sum[i] = sum[i-1] + vec[i];
            }
            for(int i=0;i<MAX_N;i++){
                dp[i][i] = 0;
                s[i][i] = i;
            }
            for(int len = 2;len<=N;len++){
                for(int i=1;i<=N;i++){
                    int j = i + len - 1;
                    if(j > N) continue;
                    for(int k=s[i][j-1];k<=s[i+1][j];k++){
                        //dp[i][j] = min(dp[i][j] , dp[i][k] + dp[k+1][j] + sum[j] - sum[i-1]);
                        if(dp[i][j] > dp[i][k] + dp[k+1][j] + sum[j] - sum[i-1]){
                            dp[i][j] = dp[i][k] + dp[k+1][j] + sum[j] - sum[i-1];
                            s[i][j] = k;
                        }
                    }
                }
            }
            cout<<dp[1][N]<<endl;
        }
        return 0;
    }
    View Code

    附:此题的升级版  HDU 3506 Monkey Party

    Monkey Party

    Problem Description

    Far away from our world, there is a banana forest. And many lovely monkeys livethere. One day, SDH(Song Da Hou), who is the king of banana forest, decides tohold a big party to celebrate Crazy Bananas Day. But the little monkeys don'tknow each other, so as the king, SDH must do something. 
    Now there are n monkeys sitting in a circle, and each monkey has a makingfriends time. Also, each monkey has two neighbor. SDH wants to introduce themto each other, and the rules are:
    1.every time, he can only introduce one monkey and one of this monkey'sneighbor. 
    2.if he introduce A and B, then every monkey A already knows will know everymonkey B already knows, and the total time for this introducing is the sum ofthe making friends time of all the monkeys A and B already knows;
    3.each little monkey knows himself; 
    In order to begin the party and eat bananas as soon as possible, SDH want toknow the mininal time he needs on introducing.  

    Input

    There is several test cases. In each case, the first line is n(1 ≤ n ≤ 1000), whichis the number of monkeys. The next line contains n positive integers(less than1000), means the making friends time(in order, the first one and the last oneare neighbors). The input is end of file. 

    Output

    For each case, you should print a line giving the mininal time SDH needs on introducing. 

    Sample Input

    8

    5 2 4 7 6 1 3 9 

    Sample Output

    105

    【题意】

    问题转化后其实就是环形石子合并,即现在有围成一圈的若干堆石子,其他条件跟其那面那题相同,问合并所需最小代价。

    【思路】

    我们需要做的是尽量向简单的问题转化,可以把前 n-1 堆石子一个个移到第 n 个后面,那样环就变成了线,即现在有 2*n-1 堆石子需要合并,我们只要求下面的式子即可。求法与上面那题完全一样。

    #include<bits/stdc++.h>
    using namespace std;
    #define LL long long
    #define fi first
    #define se second
    #define pb(a) push_back(a)
    typedef pair<int,int> pii;
    typedef pair<pii,string> pis;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int MAX_N = 2e3+7;
    int N,M,T,S;
    int dp[MAX_N][MAX_N];
    int vec[MAX_N];
    int sum[MAX_N];
    int s[MAX_N][MAX_N];
    int main() {
        while(cin>>N){
            memset(dp,0x3f,sizeof(dp));
            for(int i=1;i<=N;i++){
                scanf("%d",&vec[i]);
                vec[i+N] = vec[i];
            }
            sum[0] = 0;
            for(int i=1;i<2*N;i++){
                sum[i] = sum[i-1] + vec[i];
            }
            for(int i=0;i<MAX_N;i++){
                dp[i][i] = 0;
                s[i][i] = i;
            }
            for(int len = 2;len<=N;len++){
                for(int i=1;i<=2*N-1;i++){
                    int j = i + len - 1;
                    if(j>2*N-1) continue;
                    for(int k = s[i][j-1];k<=s[i+1][j];k++){
                        if(dp[i][j] > dp[i][k] + dp[k+1][j] + sum[j] - sum[i-1]){
                            dp[i][j] = dp[i][k] + dp[k+1][j] + sum[j] - sum[i-1];
                            s[i][j] = k;
                        }
                    }
    
                }
    
            }
    
            int ans = inf;
            for(int i=1;i<=N;i++){
                ans = min(ans,dp[i][i+N-1]);
            }
            cout<<ans<<endl;
        }
        return 0;
    }
    View Code

    2. 括号匹配问题

    Brackets

    We give the following inductive definition of a “regular brackets” sequence:

    • the empty sequence is a regular brackets sequence,
    • if s is a regular brackets sequence, then (s) and [s] are regular brackets sequences, and
    • if a andb are regular brackets sequences, thenab is a regular brackets sequence.
    • no other sequence is a regular brackets sequence

    For instance,all of the following character sequences are regular brackets sequences:

    (), [], (()), ()[], ()[()]

    while thefollowing character sequences are not:

    (, ], )(, ([)], ([(]

    Given a brackets sequence of characters a1a2 … an,your goal is to find the length of the longest regular brackets sequence that is a subsequence ofs. That is, you wish to find the largestmsuch that for indicesi1,i2, …,imwhere 1 ≤i1 <i2 < … <imn,ai1ai2 … aim is a regular bracketssequence.

    Given the initial sequence ([([]])], the longest regularbrackets subsequence is[([])].

    Input

    The input test file will contain multiple test cases. Each input test case consists of asingle line containing only the characters(,),[, and]; each input test will have length between 1 and 100, inclusive. The end-of-file is marked by a line containing the word “end” and should not be processed.

    Output

    For each input case, the program should print the length of the longest possible regular brackets subsequence on a single line.

    Sample Input

    ((()))
    ()()()
    ([]])
    )[)(
    ([][][)
    end

    Sample Output

    6
    6
    4
    0
    6

    【题意】

    给出一个的只有'(',')','[',']'四种括号组成的字符串,求最多有多少个括号满足题目里所描述的完全匹配。

    【思路】

    用 dp[i][j]表示区间 [i,j] 里最大完全匹配数。只要得到了 dp[i][j],那么就可以得到 dp[i-1][j+1]dp[i-1][j+1]=dp[i][j]+(s[i-1]与 [j+1] 匹配 ? 2 : 0)然后利用状态转移方程更新一下区间最优解即可。dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j])

    #include<cstdio>
    #include<algorithm>
    #include<iostream>
    #include<stdio.h>
    #include<cstring>
    using namespace std;
    #define LL long long
    #define fi first
    #define se second
    #define pb(a) push_back(a)
    typedef pair<int,int> pii;
    typedef pair<pii,string> pis;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int MAX_N = 1e3+7;
    int N,M,T,S;
    int dp[MAX_N][MAX_N];
    string vec;
    int main() {
        while(cin>>vec){
            if(vec == "end") break;
            memset(dp,0,sizeof(dp));
            N = vec.length();
            for(int len = 2;len<=N;len++){
                for(int i=0;i<N;i++){
                    int j = i + len - 1;
                    if(j >= N) continue;
                    if((vec[i] == '(' && vec[j] == ')')||(vec[i] == '[' && vec[j] == ']')){
                        dp[i][j] = dp[i+1][j-1] + 2;
                    }
                    for(int k = i ; k < j ; k ++){
                        dp[i][j] = max(dp[i][j]  , dp[i][k] + dp[k+1][j]);
                    }
                }
            }
            cout<<dp[0][N-1]<<endl;
    
        }
        return 0;
    }
    View Code

    【变题】 题目链接

    括号匹配(二)

    给你一个字符串,里面只包含 "(",")","[","]" 四种符号,请问你需要至少添加多少个括号才能使这些括号匹配起来。
    如:
    [] 是匹配的
    ([])[] 是匹配的
    ((] 是不匹配的
    ([)] 是不匹配的

    输入

    第一行输入一个正整数 N,表示测试数据组数 (N<=10)
    每组测试数据都只有一行,是一个字符串 S,S 中只包含以上所说的四种字符,S 的长度不超过 100

    输出

    对于每组测试数据都输出一个正整数,表示最少需要添加的括号的数量。每组测试输出占一行

    样例输入

    4

    []

    ([])[]

    ((]

    ([)]

    样例输出

    0

    0

    3

    2

    【题意】

    上一题求的是满足完美匹配的最大括号数量,而这题问的是使所有括号完美匹配需要添加的最小括号数量

    【思路】

    显然,要使添加的括号尽量少,我们需要使原来的括号序列尽可能多得匹配,即先求最大匹配数量 (跟上题一样),那么还剩下一些没有匹配的括号,我们就需要依次加上一个括号使它们得到匹配。综上所述,所求 = 原序列括号数量 - 最大匹配括号数量。(因此此题的代码与上题几乎一致)。

    #include<bits/stdc++.h>
    using namespace std;
    #define LL long long
    #define fi first
    #define se second
    #define pb(a) push_back(a)
    typedef pair<int,int> pii;
    typedef pair<pii,string> pis;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int MAX_N = 1e3+7;
    int N,M,T,S;
    int dp[MAX_N][MAX_N];
    string vec;
    int main() {
        cin>>T;
        while(T--){
            cin>>vec;
            memset(dp,0,sizeof(dp));
            N = vec.length();
            for(int len = 2;len<=N;len++){
                for(int i=0;i<N;i++){
                    int j = i + len - 1;
                    if(j >= N) continue;
                    if((vec[i] == '(' && vec[j] == ')')||(vec[i] == '[' && vec[j] == ']')){
                        dp[i][j] = dp[i+1][j-1] + 2;
                    }
                    for(int k = i ; k < j ; k ++){
                        dp[i][j] = max(dp[i][j]  , dp[i][k] + dp[k+1][j]);
                    }
                }
            }
            cout<<N - dp[0][N-1]<<endl;
    
        }
        return 0;
    }
    View Code

    3. 整数划分问题

    整数划分(四)

    暑假来了,hrdv 又要留学校在参加 ACM 集训了,集训的生活非常 Happy(ps:你懂得),可是他最近遇到了一个难题,让他百思不得其解,他非常郁闷。。亲爱的你能帮帮他吗?

    问题是我们经常见到的整数划分,给出两个整数 n , m , 要求在 n 中加入 m - 1 个乘号,将 n 分成 m 段,求出这 m 段的最大乘积

    输入

    第一行是一个整数 T,表示有 T 组测试数据
    接下来 T 行,每行有两个正整数 n,m (1<= n < 10^19, 0 < m <= n 的位数);

    输出

    输出每组测试样例结果为一个整数占一行

    样例输入

    2

    111 2

    1111 2

    样例输出

    11

    121

    【题意】

    给出一个数 n, 要求在 n 的数位间插入 (m-1) 个乘号,将 n 分成了 m 段,求这 m 段的最大乘积。

    【思路】

    用 dp[i][j] 表示从第一位到第 i 位共插入 j 个乘号后乘积的最大值。根据区间 DP 的思想我们可以从插入较少乘号的结果算出插入较多乘号的结果。方法是当我们要放第 j 的乘号时枚举放的位置。

    状态转移方程为dp[i][j]=max(dp[i][j],dp[k][j-1]*num[k+1][i])。

    其中 num[i][j] 表示从 s[i] 到 s[j] 这段连续区间代表的数值。

    #include<cstdio>
    #include<algorithm>
    #include<iostream>
    #include<stdio.h>
    #include<cstring>
    using namespace std;
    #define LL long long
    #define fi first
    #define se second
    #define pb(a) push_back(a)
    typedef pair<int,int> pii;
    typedef pair<pii,string> pis;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int MAX_N = 1e3+7;
    int N,M,T,S;
    LL dp[MAX_N][MAX_N];
    LL num[MAX_N][MAX_N];
    string vec;
    int main() {
        cin>>T;
        while(T--){
            cin>>vec>>M;
            memset(dp,0,sizeof(dp));
            memset(num,0,sizeof(num));
            N = vec.length();
            LL t = 0;
            for(int i=0;i<N;i++){
                for(int j=i;j<N;j++){
                    LL t = 0;
                    for(int k=i;k<=j;k++){
                        t *= 10;
                        t += vec[k] - '0';
                    }
                    num[i][j] = t;
                }
            }
            for(int i=0;i<N;i++){
                dp[i][0] = num[0][i];
            }
            for(int len = 1; len < M;len ++){
                for(int i=0;i<N;i++){
                    for(int k = 0;k<i;k++){
                        dp[i][len] = max(dp[i][len] , dp[k][len-1]*num[k+1][i]);
                    }
                }
            }
            cout<<dp[N-1][M-1]<<endl;
    
        }
        return 0;
    }
    View Code

    4. 凸多边形三角划分问题

    给定一个具有 N(N<=50) 个顶点 (从 1 到 N 编号) 的凸多边形,每个顶点的权值已知。问如何把这个凸多边形划分成 N-2 个互不相交的三角形,使得这些三角形顶点的权值的乘积之和最小。

    Input

    第一行为顶点数 N,第二行为 N 个顶点(从 1 到 N)的权值。

    Output

    乘积之和的最小值。题目保证结果在 int 范围内。

    Sample Input

    5

    1 6 4 2 1

    5

    121 122 123 245 231

    Sample Output

    34

    12214884

    【题意】

    给出一个数 n, 要求在 n 的数位间插入 (m-1) 个乘号,将 n 分成了 m 段,求这 m 段的最大乘积。

    【思路】

    用 dp[i,j] 表示从顶点 i 到顶点 j 的凸多边形三角剖分后所得到的最大乘积。那么可以写出状态转移方程,并通过枚举分割点来转移。

    dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]+a[i]*a[k]*a[j])。

    #include <cstdio>
    #include <queue>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    #define mst(a,b) memset((a),(b),sizeof(a))
    #define rush() int T;scanf("%d",&T);while(T--)
    
    typedef long long ll;
    const int maxn = 55;
    const ll mod = 1e9+7;
    const int INF = 0x3f3f3f3f;
    const double eps = 1e-9;
    
    int a[maxn];
    int dp[maxn][maxn];
    
    int main()
    {
        int n;
        while(~scanf("%d",&n))
        {
            for(int i=1;i<=n;i++)
            {
                scanf("%d",&a[i]);
            }
            mst(dp,0);
            for(int len=3;len<=n;len++)
            for(int i=1;i<=n;i++)
            {
                int j=i+len-1;
                if(j>n) break;
                dp[i][j]=INF;
                for(int k=i+1;k<j;k++)
                {
                    dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]+a[i]*a[k]*a[j]);
                }
            }
            printf("%d
    ",dp[1][n]);
        }
        return 0;
    }
    View Code

    四、拓展例题

    1. HDOJ 2513 Cake slicing

    题目链接

    Cake slicing

    A rectangular cake with a grid of m*n unit squares on its top needs to be slicedinto pieces. Several cherries are scattered on the top of the cake with at mostone cherry on a unit square. The slicing should follow the rules below:
    1.  each piece is rectangular or square;
    2.  each cutting edge is straight and along a grid line;
    3.  each piece has only one cherry on it;
    4.  each cut must split the cake you currently cut two separate parts
    For example, assume that the cake has a grid of 3*4 unit squares on its top,and there are three cherries on the top, as shown in the figure below. 

    One allowable slicing is as follows. 

    For this way of slicing , the total length of the cutting edges is 2+4=6.
    Another way of slicing is  

    In this case, the total length of the cutting edges is 3+2=5.
    Give the shape of the cake and the scatter of the cherries , you are supposedto find
    out the least total length of the cutting edges. 

    Input

    The input file contains multiple test cases. For each test case:
    The first line contains three integers , n, m and k (1≤n, m≤20), where n*m isthe size of the unit square with a cherry on it . The two integers showrespectively the row number and the column number of the unit square in thegrid .
    All integers in each line should be separated by blanks. 

    Output

    Output an integer indicating the least total length of the cutting edges. 

    Sample Input

    3 4 3

    1 2

    2 3

    3 2 

    Sample Output

    Case 1: 5

    【题意】

    有一个 n*m 大小的蛋糕,上面有 k 个樱桃,现在我们需要把这个蛋糕切成 k 份,使每份蛋糕上有一个樱桃,问最小切割长度和。(切割一刀必须切到底)

    【思路】

    用 dp[i][j][k][l]表示以 (i,j) 为左上角,(k,l)为右下角的矩形切成每份一个樱桃的最小切割长度。然后就利用区间 DP 的作用,枚举切割点,从小区间转移到大区间。由于这道题不同区间樱桃个数不同,故用递归的写法会方便些。

    #include<cstdio>
    #include<algorithm>
    #include<iostream>
    #include<stdio.h>
    #include<cstring>
    using namespace std;
    #define LL long long
    #define fi first
    #define se second
    #define pb(a) push_back(a)
    typedef pair<int,int> pii;
    typedef pair<pii,string> pis;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int MAX_N = 25;
    int N,M,T,S;
    int dp[MAX_N][MAX_N][MAX_N][MAX_N];
    int vec[MAX_N][MAX_N];
    int dfs(int x1,int y1,int x2,int y2){
        if(dp[x1][y1][x2][y2] != -1) return dp[x1][y1][x2][y2];
        int cnt = 0;
        for(int i=x1;i<=x2;i++){
            for(int j=y1;j<=y2;j++){
                if(vec[i][j]) cnt ++;
            }
        }
        if(cnt <= 1) {
            dp[x1][y1][x2][y2] = 0;
            return 0;
        }
        int minn = inf;
        for(int i=x1;i<x2;i++){
            minn = min(minn , dfs(x1,y1,i,y2) + dfs(i+1,y1,x2,y2) + (y2-y1+1));
        }
        for(int i=y1;i<y2;i++){
            minn = min(minn , dfs(x1,y1,x2,i) + dfs(x1,i+1,x2,y2) + (x2-x1+1));
        }
        dp[x1][y1][x2][y2] = minn;
        return minn;
    }
    int main() {
        T = 1;
        while(cin>>N>>M>>S){
            int x,y;
            memset(vec,0,sizeof(vec));
            memset(dp,-1,sizeof(dp));
            for(int i=0;i<S;i++){
                scanf("%d%d",&x,&y);
                vec[x][y] = 1;
            }
            int ans = dfs(1,1,N,M);
            printf("Case %d: %d
    ",T,ans);
            T++;
        }
        return 0;
    }
    View Code
    2. HDOJ 2476 String painter

    题目链接

    String painter

    There are two strings A and B with equal length. Both strings are made up of lowercase letters. Now you have a powerful string painter. With the help of thepainter, you can change a segment of characters of a string to any othercharacter you want. That is, after using the painter, the segment is made up ofonly one kind of character. Now your task is to change A to B using stringpainter. What’s the minimum number of operations? 

    Input

    Input contains multiple cases. Each case consists of two lines:
    The first line contains string A.
    The second line contains string B.
    The length of both strings will not be greater than 100. 

    Output

    A single line contains one integer representing the answer. 

    Sample Input

    zzzzzfzzzzz

    abcdefedcba

    abababababab

    cdcdcdcdcdcd 

    Sample Output

    6

    7

    【题意】

    给出字符串 A 和 B,每一次我们可以使用一种颜色(用字母代替)刷任意一个连续子序列,问将字符串 A 变成字符串 B 最少需要刷多少次。

    【思路】

    分析了很久,发现直接去考虑将 A 串刷成 B 串非常困难。于是我们考虑间接转化。

    用 dp[i][j]表示把将一个空白串 [i,j] 刷成 B 字符串对应位置的最小次数。

    用 ans[i]表示把 A 串的区间 [1,i] 刷成 B 串需要的最小次数。

    然后状态转移一下就 OK 啦。

    #include<bits/stdc++.h>
    using namespace std;
    #define LL long long
    #define fi first
    #define se second
    #define pb(a) push_back(a)
    typedef pair<int,int> pii;
    typedef pair<pii,string> pis;
    const int inf = 0x3f3f3f3f;
    const LL INF = 0x3f3f3f3f3f3f3f3f;
    const int MAX_N = 1e2+7;
    int N,M,T,S;
    int dp[MAX_N][MAX_N];
    int ans[MAX_N];
    string s1,s2;
    int main() {
        while(cin>>s1>>s2){
            memset(dp,0,sizeof(dp));
            memset(ans,0x3f,sizeof(ans));
            int len = s1.length();
            for(int i=0;i<=len;i++){
                dp[i][i] = 1;
            }
            //一个空串转化为s2的dp
            for(int j=1;j<len;j++){
                for(int i=j-1;i>=0;i--){
                    dp[i][j] = dp[i][j-1] + 1;
                    for(int k=i;k<j;k++){
                        if(s2[j] == s2[k]){
                            dp[i][j] = min(dp[i][j] , dp[i][k-1] + dp[k][j-1]);
                        }
                    }
                }
            }
            //cout<<"...."<<dp[0][len-1]<<endl;
            for(int i=0;i<len;i++){
                ans[i] = dp[0][i];
                if(s1[i] == s2[i]){
                    ans[i] = min(ans[i] , ans[i-1]);
                }
                else{
                    for(int j = 0;j<i;j++){
                        ans[i] = min(ans[i] , ans[j] + dp[j+1][i]);
                    }
                }
            }
            printf("%d
    ",ans[len-1]);
        }
        return 0;
    }
    View Code

     本博客转载自:区间dp小结

  • 相关阅读:
    [转载]使用SecureCRT进行vim编辑的时候,小键盘变成字母的解决办法
    [转载]运行中的程序突然出现"Killed"原因
    [转载]IPv6地址表示方法详解
    【转载】深入浅出Pairwise算法
    [转载]不要用强制方法杀掉python线程
    [转载]Python SQLite3的问题sqlite3.ProgrammingError: SQLite objects created in a thread
    SQL语句中distinct的分页和查询数据数量
    SQL语句中获取时间的方法
    SQLService中使用SQL语句书写分页
    使用Angular下拉自动加载
  • 原文地址:https://www.cnblogs.com/doggod/p/9720669.html
Copyright © 2011-2022 走看看