CodeForces 67 C.Sequence of Balls(dp)

Description

给出两个字符串 A B ,可以对 A 字符串进行以下四种操作:

1.在任意位置插入任意字符,代价为 t i

2.删去任意位置的字符,代价为 t d

3.替代任意位置的字符,代价为 t r

4.交换任意两个相邻的字符,代价为 t e

保证 2 t e t i + t d ,问如何以最小代价将 A 字符串变成 B 字符串

Input

第一行输入四个整数 t i , t d , t r , t e ,之后输入两个字符串 A B ( 0 < t i , t d , t r , t e 100 , 1 | A | , | B | 4000 )

Output

输出最小代价

Sample Input

1 1 1 1
youshouldnot
thoushaltnot

Sample Output

5

Solution

由于 2 t e t i + t d ,若要通过不断交换使得某个字符移动超过一个位置,其代价超过了删掉该字符之后在需要的位置插入指定字符,故操作过程中只需考虑相邻两个字符交换,但是由于删除操作的存在,仍需考虑任意两个字符的交换,但是代价为一次交换的代价和删去这两个字符之间所有字符的代价之和(相当于删去中间字符使得这两个字符相邻)

d p [ i ] [ j ] 表示 A 的前 i 个字符匹配 B 的前 j 个字符所需的最小代价,则有

删去 a [ i ] d p [ i ] [ j ] = m i n ( d p [ i ] [ j ] , d p [ i 1 ] [ j ] + t d ) , i > 0

插入 b [ j ] d p [ i ] [ j ] = m i n ( d p [ i ] [ j ] , d p [ i ] [ j 1 ] + t i ) , j > 0

替换 a [ i ] d p [ i ] [ j ] = m i n ( d p [ i ] [ j ] , d p [ i 1 ] [ j 1 ] + a [ i ] = b [ j ] ? 0 : t r ) , i , j > 0

交换使得 a [ i ] , b [ j ] 匹配:找到 A i 位置之前第一个 b [ j ] 的位置 x 以及 B j 位置之前第一个 a [ i ] 的位置 y ,首先把 x i 之间的都删掉,记入删除代价,然后交换 a [ x ] a [ i ] 使得 a [ x ] = b [ y ] , a [ i ] = b [ j ] ,最后在这两个字符之间加入 B 串中 y j 之间的字符,记入插入代价,假设总代价为 c o s t ,那么有 d p [ i ] [ j ] = m i n ( d p [ i ] [ j ] , d p [ x 1 ] [ y 1 ] + c o s t ) , x , y > 0

最后 d p [ | A | ] [ | B | ] 即为答案

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=4005;
int n,m,val[5],dp[maxn][maxn],pos[27],prea[maxn][27],preb[maxn][27];
char a[maxn],b[maxn];
int main()
{
    for(int i=1;i<=4;i++)scanf("%d",&val[i]);
    scanf("%s%s",a+1,b+1);
    n=strlen(a+1),m=strlen(b+1);
    memset(pos,0,sizeof(pos));
    for(int i=1;i<=n;i++)
    {   
        for(int j=0;j<26;j++)prea[i][j]=pos[j];
        pos[a[i]-'a']=i;
    }
    memset(pos,0,sizeof(pos));
    for(int i=1;i<=m;i++)
    {   
        for(int j=0;j<26;j++)preb[i][j]=pos[j];
        pos[b[i]-'a']=i;
    }
    memset(dp,INF,sizeof(dp));
    dp[0][0]=0;
    for(int i=0;i<=n;i++)
        for(int j=0;j<=m;j++)
        {
            if(j)dp[i][j]=min(dp[i][j],dp[i][j-1]+val[1]);
            if(i)dp[i][j]=min(dp[i][j],dp[i-1][j]+val[2]);
            if(i&&j)dp[i][j]=min(dp[i][j],dp[i-1][j-1]+(a[i]==b[j]?0:val[3]));
            int pa=prea[i][b[j]-'a'],pb=preb[j][a[i]-'a'];
            if(pa&&pb)
            {
                int temp=(j-pb-1)*val[1]+(i-pa-1)*val[2]+val[4];
                dp[i][j]=min(dp[i][j],dp[pa-1][pb-1]+temp); 
            }
        }
    printf("%d\n",dp[n][m]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/v5zsq/article/details/81041598
67