zoukankan      html  css  js  c++  java
  • String painter(区间DP)

    There are two strings A and B with equal length. Both strings are made up of lower case letters. Now you have a powerful string painter. With the help of the painter, you can change a segment of characters of a string to any other character you want. That is, after using the painter, the segment is made up of only one kind of character. Now your task is to change A to B using string painter. 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的最小操作次数。
    #include <iostream>
    #include <cstring>
    #include <string>
    #include <algorithm>
    using namespace std;
    int dp[105][105],ans[105];///dp[i][j]中的i,j表示左右端点
    int main()
    {
        string a,b;
        while(cin>>a>>b)
        {
            memset(dp,0,sizeof dp);
            for(int j=0;b[j];j++)///预处理一段区间内的最小次数
                for(int i=j;i>=0;i--)
                {
                    dp[i][j]=dp[i+1][j]+1;
                    for(int k=i+1;k<=j;k++)
                        if(b[i]==b[k])
                            dp[i][j]=min(dp[i][j],dp[i+1][k]+dp[k+1][j]);
                }
            for(int i=0;a[i];i++)
            {
                ans[i]=dp[0][i];
                if(a[i]!=b[i])///找更少的次数
                    for(int j=0;j<i;j++)
                        ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
                else///不刷
                    ans[i]=ans[i-1];
            }
            cout<<ans[b.size()-1]<<'
    ';
        }
        return 0;
    }
    
    
  • 相关阅读:
    Jrain'Lのvueblog
    前端知识整理 の IMWeb
    js编程小练习1
    mac版本cornerstone的无限期破解方法(转)
    教你解锁被锁住的苹果mac电脑的文件跟文件夹,同时也可删除被锁的文件跟文件夹(转)
    Mac下配置svn服务器
    ios 查看模拟器路径以及应用的文件夹
    python怎么解压压缩的字符串数据
    python全局变量被覆盖的问题
    PyInstaller:把你的Python转为Exe
  • 原文地址:https://www.cnblogs.com/zdragon1104/p/9143169.html
Copyright © 2011-2022 走看看