POJ 1692 Crossed Matchings

Description
There are two rows of positive integer numbers. We can draw one line segment between any two equal numbers, with values r, if one of them is located in the first row and the other one is located in the second row. We call this line segment an r-matching segment. The following figure shows a 3-matching and a 2-matching segment.
We want to find the maximum number of matching segments possible to draw for the given input, such that:
1. Each a-matching segment should cross exactly one b-matching segment, where a != b .
2. No two matching segments can be drawn from a number. For example, the following matchings are not allowed.
Write a program to compute the maximum number of matching segments for the input data. Note that this number is always even.


【题目分析】
    交叉匹配,相当于4个一组,然后想到了dp的方法。若a[i]==b[j],就跳过。如果是a[i]!=b[j]。那就试图找到前面的最近的可以和他们组成一对的数字。然后方程就是:dp[i][j]=max(dp[i][j],dp[k1-1][k2-1]+2);
   


【代码】

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int a[101],b[101];
int dp[101][101];
int main()
{
    int tt,n,m;
    cin>>tt;
    while (tt--)
    {
        cin>>n>>m;
        for (int i=1;i<=n;++i) cin>>a[i];
        for (int j=1;j<=m;++j) cin>>b[j];
        memset(dp,0,sizeof dp);
        for (int i=1;i<=n;++i)
            for (int j=1;j<=m;++j)
            {
                dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                if (a[i]==b[j]) continue;
                int k1=0,k2=0;
                for (int k=i-1;k>=1;--k) if (a[k]==b[j]) {k1=k; break;}
                for (int k=j-1;k>=1;--k) if (b[k]==a[i]) {k2=k; break;}
                if (k1&&k2) dp[i][j]=max(dp[i][j],dp[k1-1][k2-1]+2);
            }
        cout<<dp[n][m]<<endl;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值