Lightoj 1422 (interval DP)

Source: Internet
Author: User

Topic Links: Lightoj 1422

Problem Solving Ideas:
In fact, a glance at the past did not expect to be DP, but drew a connection diagram, that is, two of the same number with a straight line, the requirement is actually a longest non-interlaced sequence. Then came the thought of a symmetry, such as the example of "5 1 2 3 2 1", so there is no solution. But also because of the thought of this situation reminds me that this is an interval DP problem, so the solution is very simple.

Code:

#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define INF

0x3f3f3f3f using namespace std;

int n,dp[105][105],a[105];
    int main () {int t,t=0;
    scanf ("%d", &t);
        while (t<t) {scanf ("%d", &n);
        for (int i=1;i<=n;i++) {scanf ("%d", &a[i]);

        } for (int i=1;i<=n;i++) for (int j=i;j<=n;j++) dp[i][j]=j-i+1;        

        for (int i=1;i<n;i++) dp[i][i+1]=2-(a[i]==a[i+1]);
                    for (int l=2;l<n;l++) {for (int i=1;i<=n-l;i++) {if (A[i]==a[i+l])
                dp[i][i+l]=dp[i+1][i+l-1]+1;
                for (int j=i;j<=i+l;j++) {dp[i][i+l]=min (dp[i][i+l], dp[i][j]+dp[j][i+l]-1);
    }}} printf ("Case%d:%d\n", ++t,dp[1][n]);
} return 0; }

Summary:
It's a good question to turn a seemingly dynamic plan into a dynamic plan, quite magical.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.