zoukankan      html  css  js  c++  java
  • POJ 1159 回文LCS滚动数组优化

    详细解题报告可以看这个PPT

    这题如果是直接开int 5000 * 5000  的空间肯定会MLE,优化方法是采用滚动数组。

    原LCS转移方程 : 

    dp[i][j] = dp[i - 1][j] + dp[i][j  -1]
    

    因为 dp[i][j] 只依赖于 dp[i - 1][j] 和 dp[i][j - 1]

    所以可以采用滚动数组如下:

    dp[i % 2][j] = dp[(i - 1) % 2][j] + dp[i % 2][j - 1]
    

    可以实现节省空间的方法

    答案存储在 dp[n % 2][n] 中

    source code:

    //#pragma comment(linker, "/STACK:16777216") //for c++ Compiler
    #include <stdio.h>
    #include <iostream>
    #include <cstring>
    #include <cmath>
    #include <stack>
    #include <queue>
    #include <vector>
    #include <algorithm>
    #define ll long long
    #define Max(a,b) (((a) > (b)) ? (a) : (b))
    #define Min(a,b) (((a) < (b)) ? (a) : (b))
    #define Abs(x) (((x) > 0) ? (x) : (-(x)))
    
    using namespace std;
    
    const int INF  = 0x3f3f3f3f;
    const int MAXN = 500;
    
    int dp[2][5005];
    
    int main(){
        int i, j, t, k, n, m;
        string str1, str2;
        while(EOF != scanf("%d",&n)){
            cin >> str1;
            str2 = str1;
            reverse(str1.begin(), str1.end());
            memset(dp, 0, sizeof(dp));
            for(i = 1; i <= n; ++i){
                for(j = 1; j <= n; ++j){
                    if(str1[i - 1] == str2[j - 1]){
                        dp[i % 2][j] = max(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]);
                    }
                }
            }
            cout << n - dp[n % 2][n] << endl;   //answer = X.length() - LCS(X, Y)
        }
        return 0;
    }
  • 相关阅读:
    了解 Spring Data JPA
    Spring MVC 方法注解拦截器
    Spring MVC拦截器+注解方式实现防止表单重复提交
    java中return语句的用法总结
    equal方法在String类与Object类中的区别
    instanceof用法
    EL 简介及用法
    JAVA 四大域对象总结
    JSP基本语法
    Servlet请求转发 RequestDispatcher接口知识点
  • 原文地址:https://www.cnblogs.com/wushuaiyi/p/4138793.html
Copyright © 2011-2022 走看看