您的位置:首页 > 其它

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

2015-08-06 15:00 363 查看

【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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态规划