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.
Input
Output
Sample Input
Sample Output
题目大意:上下2排数据,找一个满足条件的最大匹配数(条件是任意一个匹配的连线都要被至少另一个不一样的匹配穿过)!
解题思路:opt[i][j]为 up[] 数组前 i 个数与 down[] 数组前 j 个数的最大匹配.递推关系:
opt[i][j] = max{ opt[i-1][j], opt[i][j-1], opt[a-1][b-1] + 2}
>_< :上式 a,b 的取值须满足 (1 <= a < i) && (1 <= b < j) 并且存在匹配 (up[a] == down[j]) && (down[b] == up[i]) && (up[a] != up[i])
#include<iostream>
#include<string.h>
using namespace std;
int M;
int N1,N2;
int up[],down[];
int opt[][];
int main(){
cin>>M;
while(M--){
cin>>N1>>N2;
memset(opt,,sizeof(opt));
for(int i=;i<=N1;i++)cin>>up[i];
for(int j=;j<=N2;j++)cin>>down[j]; for(int i=;i<=N1;i++){
for(int j=;j<=N2;j++){
opt[i][j]= opt[i-][j]>opt[i][j-] ? opt[i-][j]:opt[i][j-];
if(up[i]!=down[j]){//只有最后2个不一样时才有可能都和前面的有匹配
int t=;
for(int a=;a<i;a++){
for(int b=;b<j;b++){//遍历查找满足条件的t
if(up[a]==down[j] && up[i]==down[b] && t<opt[a-][b-]+)
t=opt[a-][b-]+;
}
}
opt[i][j]=opt[i][j]>t ? opt[i][j]:t;
}
}
} cout<<opt[N1][N2]<<'\n';
}return ;
}