zoukankan      html  css  js  c++  java
  • 动态规划(DP),压缩状态,插入字符构成回文字符串

    题目链接:http://poj.org/problem?id=1159

    解题报告:

    1、LCS的状态转移方程为

    if(str[i-1]==str[j-1])
      dp[i][j]=dp[i-1][j-1]+1;
    else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
    

    2、由于开不了dp[5005][5005],于是考虑到压缩状态

    这里采用滚动数组方式,LCS的状态转移方程可以改写为

    if(str1[i-1]==str2[j-1])
    {
        dp[i%2][j]=dp[(i-1)%2][j-1]+1;
    }
    else dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1]);
    • Source Code
    #include <stdio.h>
    #include <algorithm>
    #include <string.h>
    #include <iostream>
    #define MAX 5005
    
    using namespace std;
    ///LCS的状态转移方程,d[i][j]=max(d[i-1][j],d[i][j-1]);
    ///LCS的滚动数组形式的状态转移方程,d[i%2][j]=max(d[(i-1)%2][j],d[i%2][j-1])
    int dp[2][MAX];///滚动数组
    
    int main()
    {
        char str1[MAX],str2[MAX];
        int n;
        cin>>n;
        cin>>str1;
        for(int i=0; i<n; i++)
            str2[n-i-1]=str1[i];
        memset(dp,0,sizeof(dp));
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
            {
                if(str1[i-1]==str2[j-1])
                {
                    dp[i%2][j]=dp[(i-1)%2][j-1]+1;
                }
                else dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1]);
            }
        }
        printf("%d
    ",n-dp[n%2][n]);
        return 0;
    }
    

      

      

  • 相关阅读:
    EditPlus保存文件时不生成其备份文件的方法
    一台电脑同时运行多个tomcat配置方法
    Dom4j写XML
    .....
    编程备忘录
    背包问题
    chrome新版不再支持-webkit-text-size-adjust
    安装grunt需要的grunt插件
    初学web前端
    心情烦躁、、
  • 原文地址:https://www.cnblogs.com/TreeDream/p/5229050.html
Copyright © 2011-2022 走看看