Analysis for POJ 3356: DP algorithm

  1. Question meaning: What is the least steps it takes for you changing a string to another string, provided that you can either add, delete, or change.

  2. DP algorithm:
    a) dp[i][j] is the least steps it take to transform the first i parts in the first string to the first j parts in the second string.
    b) DP algorithm considers from the ending, so the sub-statements for dp[i][j] are dp[i-1][j-1], dp[i-1][j], and dp[i][j-1].
    c) Initialization: dp[0][i]=dp[i][0]=i.
    d) Function transformation equation: dp[i-1][j-1];
    e) If the i character of the first string equals to the j character of the second string, then transform, else + 1.
    f) dp[i-1][j] represents the number of steps it takes for deleting the i character of the first string and adding the i-1 characters to form the j element in the second string; similar with dp[i-1][j], dp[i][j-1] inserts the first string with the j character and adds the original i characters to form the j – 1 characters in the second string.
    g) Find the smallest between dp[i-1][j-1] + str1[i] == str2[j] ? 1 : 0; dp[i-1][j] + 1; dp[i][j-1] + 1;

  3. Function transformation equation:
    a) If we want to add A[i] after B[j], then at least we need dp[i][j] = dp[i-1][j] + 1 steps.
    b) If we want to add B[j] after A[i], then at least we need dp[i][j] = dp[i][j-1] + 1 steps.
    c) If we want to change B[j] to be A[i], we have to consider whether B[j] == A[i]
    i. If B[j] == A[i], nothing changed, and we need 0 step.
    ii. If B[j] != A[i], we need 1 step.
    iii. Therefore, we use dp[i][j] = dp[i-1][j-1] + (A[i] == B[j]? 0 1)
    d) We just need to find the minimum from the three choices above.

  4. Boundaries: initialize dp[0][0, …, m] dp[0, …, n][0].

  5. Sample code:
    #include
    #include
    #include
    int len1,len2;
    int dp[1005][1005];
    char s1[1005],s2[1005];
    using namespace std;
    inline int min(int a,int b)
    {
    return a<b? a:b;
    }
    inline int max(int a,int b)
    {
    return a>b? a:b;
    }
    int init()
    {
    memset(dp,0,sizeof(dp));
    int tmp=max(len1,len2);
    for(int i=1;i<=tmp;++i)
    {
    dp[i][0]=dp[0][i]=i;
    }
    }
    int DP()
    {
    for(int i=1;i<=len1;++i)
    {
    for(int j=1;j<=len2;++j)
    {
    if(s1[i]==s2[j])
    dp[i+1][j+1]=min(min(dp[i+1][j]+1,dp[i][j+1]+1),dp[i][j]);
    else
    dp[i+1][j+1]=min(min(dp[i+1][j]+1,dp[i][j+1]+1),dp[i][j]+1);
    }
    }
    return dp[len1][len2];
    }
    int main()
    {
    while(cin>>len1>>s1)
    {
    cin>>len2>>s2;
    init();
    cout<<DP()<<endl;
    }
    system(“pause”);
    return 0;
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值