Dynamic programming interleaving matching problem __ Dynamic programming

Source: Internet
Author: User
Topic

Topic Analysis

The dynamic planning of the topic of understanding is not particularly deep, so read someone else's blog to learn, give a blog address staggered matching blog, said very good also very detailed, but the pretreatment is not very good written, I think of the way I wrote out, clear point.

#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace
Std
const int MAXN = 2005;
int A[MAXN],B[MAXN];

int DP1[MAXN][MAXN],DP2[MAXN][MAXN],F[MAXN][MAXN];
    void init (int n,int m) {memset (DP1, 0, sizeof (DP1));
    memset (DP2, 0, sizeof (DP2));
        for (int i = 1; I <= n; i++)//dp1 the element position {for (int j = 2; J <= M; j + +) that is closest to J and equal to A[i] in the first and first J elements of column A;
            {if (a[i] = = B[j-1]) dp1[i][j] = j-1;
        else dp1[i][j] = dp1[i][j-1];  for (int j = 1; j <= m; j)//dp2 Store the element position {for (int i = 2; I <=) in the first and J Elements of column A, the nearest position to I and equal to B[j] N
            i++) {if (b[j] = = A[i-1]) dp2[i][j] = i-1;
        else dp2[i][j] = dp2[i-1][j];
    int main () {int n,m; while (scanf ("%d%d", &n, &m)!= EOF) {for (int i = 1; I <= n; i++) scanf ("%d", &Amp;a[i]);
        for (int j = 1; j <= M; j +) scanf ("%d", &b[j]);
        Init (n, m);
        memset (f, 0, sizeof (f));  for (int i = 2; I <= n; i++) {for (int j = 2; J <= m; j) {F[i][j]   = F[i-1][j-1]; I and J do not participate in matching f[i][j] = max (F[i][j], f[i-1][j]); I do not participate in matching f[i][j] = max (F[i][j], f[i][j-1]);
                    J does not participate in the match if (A[i]!= b[j])//Front has the number that can match, at the same time found is the closest to the i,j, because this must be the best {
                    int ip = DP2[I][J],JP = Dp1[i][j];
                if (IP && jp) f[i][j] = max (F[i][j], f[ip-1][jp-1] + 2);
    } printf ("%d\n", F[n][m]);
return 0;
 }

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.