• 动态规划 | 最长回文子串 1040


    部分正确(19分)代码:

    #include <stdio.h>
    #include <memory.h>
    #include <math.h>
    #include <string>
    #include <cstring>
    #include <vector>
    #include <set>
    #include <stack>
    #include <queue>
    #include <algorithm>
    #include <map>
    
    
    #define I scanf
    #define OL puts
    #define O printf
    #define F(a,b,c) for(a=b;a<c;a++)
    #define FF(a,b) for(a=0;a<b;a++)
    #define FG(a,b) for(a=b-1;a>=0;a--)
    #define LEN 2000
    #define MAX (1<<30)-1
    #define V vector<int>
    
    using namespace std;
    
    char s[LEN];
    int dp[LEN][LEN];
    
    int main(){
    //    freopen("I:\pat\动态规划\1040.txt","r",stdin);
        int n,i,j,v;
        gets(s);
        n=strlen(s);
        FF(i,n){
            dp[i][i]=1;
        }
        int ans=0;
        for(v=1;v<n;v++){
            for(i=0;i+v<n;i++){
                j=i+v;
                if(s[i]==s[j]){
                    dp[i][j]=dp[i+1][j-1]+2;
                }
                ans=max(ans,dp[i][j]);
            }
        }
        O("%d",ans);
        return 0;
    }
    View Code

    AC代码(按照算法笔记修改):

    #include <stdio.h>
    #include <memory.h>
    #include <math.h>
    #include <string>
    #include <cstring>
    #include <vector>
    #include <set>
    #include <stack>
    #include <queue>
    #include <algorithm>
    #include <map>
    
    
    #define I scanf
    #define OL puts
    #define O printf
    #define F(a,b,c) for(a=b;a<c;a++)
    #define FF(a,b) for(a=0;a<b;a++)
    #define FG(a,b) for(a=b-1;a>=0;a--)
    #define LEN 2000
    #define MAX (1<<30)-1
    #define V vector<int>
    
    using namespace std;
    
    char s[LEN];
    int dp[LEN][LEN];
    
    int main(){
    //    freopen("I:\pat\动态规划\1040.txt","r",stdin);
        int n,i,j,v,ans;
        gets(s);
        n=strlen(s);
        //边界 
        ans=1;
        FF(i,n){
            dp[i][i]=1;
            if(i<n-1 && s[i]==s[i+1]){
                 dp[i][i+1]=1;
                 ans=2;
            }
        }
        for(v=2;v<n;v++){
            for(i=0;i+v<n;i++){
                j=i+v;
                if(s[i]==s[j] && dp[i+1][j-1]==1){
                    dp[i][j]=1;
                    ans=v+1;
                }
            }
        }
        O("%d",ans);
        return 0;
    }
  • 相关阅读:
    第三次作业——《原型设计》
    第二次作业《熟悉使用工具》
    跟着《构建之法》学习软件工程(第一次作业)
    纯js代码实现手风琴特效
    HTML5
    为什么做前端要做好SEO
    让div盒子相对父盒子垂直居中的几种方法
    模板artTemplate
    bootstrap兼容问题
    移动常用的类库
  • 原文地址:https://www.cnblogs.com/TQCAI/p/8572861.html
Copyright © 2020-2023  润新知