POJ 1692 Crossed Matchings (dp ).

Source: Internet
Author: User

POJ 1692 Crossed Matchings (dp ).

~~~~

Question: Give a sequence of two numbers, and find the maximum number of upper and lower matching groups.
Matching rules:
1. The matching numbers must be the same.
2. Each matching must have only one matching that is matched with each other, and the matching numbers must be different.
3. A single number can only be matched once.

For the adaptation of the longest common subsequence, f [I] [j] indicates the optimal value of matching between the first I digit of the first sequence and the first j digit of the second sequence.

State Transfer: f [I] [j] = max (f [P-1] [q-1] + 2, max (f [I-1] [j], f [I] [J-1])

& (A [p] = B [j], B [q] = a [I]);

* Updating f [I] [j] with f [P-1] [q-1] ensures that a single number can only be matched once.

Question link: http://poj.org/problem? Id = 1692

~~~~

#include
 
  #include
  
   #include#include
   
    #include
    
     #define N 1000using namespace std;int f[N][N];int a[N],b[N];int main(){    int t;    scanf("%d",&t);    while(t--)    {        int n,m;        scanf("%d%d",&n,&m);        int i,j,p,q;        for(i=1;i<=n;i++)            scanf("%d",&a[i]);        for(j=1;j<=m;j++)            scanf("%d",&b[j]);        memset(f,0,sizeof(f));        for(i=1;i<=n;i++)        {            for(j=1;j<=m;j++)            {                for(q=j-1;q>0;q--)                    if(b[q]==a[i]) break;                for(p=i-1;p>0;p--)                    if(a[p]==b[j]) break;                if(p>0 && q>0 && a[i]!=b[j])   //~~~                    f[i][j]=max(f[p-1][q-1]+2,max(f[i][j-1],f[i-1][j]));                else                    f[i][j]=max(f[i][j-1],f[i-1][j]);            }        }        printf("%d\n",f[n][m]);    }    return 0;}
    
   
  
 


Related Article

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.