HDOJ 4745 (区间DP)

the problem is here

this is a very typical range dp question ,and I made some comment right after the code down here ,the main stream of the quiz is find the longest Palindrome sub-sequence in range of [i,j],and the find the maximum of them.

#include <bits/stdc++.h>
#include <cstring>
#define ll long long
#define maxn 1005
using namespace std;
int s[maxn],dp[maxn][maxn];
int main()
{
    int n;
    while(cin>>n)
    {
        if(!n) break;
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
            cin>>s[i];
            dp[i][i] = 1;
        }
        for(int i=1;i<=n-1;i++)   //length?
        {
            for(int j = 1;i+j<=n;j++)  //start point?
            {
                int k =  i+j;    // end point?
                dp[j][k] = max(dp[j][k],max(dp[j+1][k],dp[j][k-1]));
                if(s[k] == s[j])
                {
                    dp[j][k] = max(dp[j][k],dp[j+1][k-1]+2);  //2 represent the length of the two matched number
                }
            }
        }
        int ans =0;
        for(int i=1;i<=n;i++)
        {
            ans = max(ans,dp[1][i]+dp[i+1][n]);
        }
        cout<<ans<<endl;
    }
    return 0;
}
发布了188 篇原创文章 · 获赞 11 · 访问量 5万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览