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;
}
}