动态规划_线性结构例题_Color Length(UVA1625)

【Color Length(UVA1625)】


【解析】

很难想到这是一个DP问题,看到的题意和思路都不太明晰,于是决定自己亲手做一做。
建立一个模型,求出状态:str1、str2分别拿出i、j个字符时的最优解。
dp(i,j) = min{dp(i-1,j), dp(i, j-1)} + temp
其中,temp是还有多少个字符没有结束。可由预处理简化判断。


【代码】

#include<iostream>
#include<cstring>
#include<string>
using namespace std;

const int maxn = 5000;
const int INF = 1<<30;
int dp[maxn+10][maxn+10];
int color1[32][2], color2[32][2];

int main()
{
    string str1, str2;
    int n;
    cin>>n;
    while(n--)
    {
        str1.clear(); str2.clear();
        cin>>str1>>str2;
        memset(color1, -1, sizeof(color1));
        memset(color2, -1, sizeof(color2));
        int len1 = str1.length(), len2 = str2.length();
        for(int i=0; i<len1; i++)
            if(color1[str1[i]-'A'][0]==-1)
            {
                color1[str1[i]-'A'][0] = i;
                color1[str1[i]-'A'][1] = i;
            }
            else color1[str1[i]-'A'][1] = i;

        for(int i=0; i<len2; i++)
            if(color2[str2[i]-'A'][0]==-1)
            {
                color2[str2[i]-'A'][0] = i;
                color2[str2[i]-'A'][1] = i;
            }
            else color2[str2[i]-'A'][1] = i;

        for(int i=0; i<=len1; i++)
            for(int j=0; j<=len2; j++)
            {

                int ans;
                ans = 0;
                for(int k=0; k<26; k++)
                    if(((color1[k][0]>-1 && color1[k][0]<=i-1) || (color2[k][0]>-1 && color2[k][0]<=j-1)) && (color1[k][1]>i-1 || color2[k][1]>j-1))
                        ans++;
                dp[i][j] = min(i-1>=0?dp[i-1][j]:INF, j-1>=0?dp[i][j-1]:INF) + ans;
                if(!i && !j) dp[0][0] = 0;
            }
        cout<<dp[len1][len2]<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值