HDOJ 4745 (区间DP)

来源:互联网 发布:java注册登录代码 编辑:程序博客网 时间:2024/06/06 05:13

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 1005using 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;}
原创粉丝点击