经典DP,想了很久,开始想复杂了。
#include <iostream> using namespace std; #define MAXNUM 100 int mymax(int a, int b) { return (a>b) ? a:b; } int main() { int case_n; int a_n, b_n; int i, j; int a[MAXNUM], b[MAXNUM]; int match[MAXNUM][MAXNUM]; int max_a2b[MAXNUM][MAXNUM], max_b2a[MAXNUM][MAXNUM]; cin >>case_n; while (case_n--) { cin >>a_n>>b_n; for (i=1; i<=a_n; ++i) cin >>a[i]; for (i=1; i<=b_n; ++i) cin >>b[i]; for (i=0; i<=a_n; ++i) { match[i][0] = 0; max_a2b[i][0] = 0; } for (i=0; i<=b_n; ++i) { match[0][i] = 0; max_b2a[i][0] = 0; } for (i=1; i<=a_n; ++i) for (j=1; j<=b_n; ++j) { if (a[i] == b[j-1]) max_a2b[i][j] = j-1; else max_a2b[i][j] = max_a2b[i][j-1]; } for (i=1; i<=b_n; ++i) for (j=1; j<=a_n; ++j) { if (b[i] == a[j-1]) max_b2a[i][j] = j-1; else max_b2a[i][j] = max_b2a[i][j-1]; } int pos_b, pos_a; for (i=1; i<=a_n; ++i) { for (j=1; j<=b_n; ++j) { match[i][j] = mymax(match[i-1][j], match[i][j-1]); pos_b = max_a2b[i][j]; pos_a = max_b2a[j][i]; if (pos_b>0 && pos_a>0 && a[i] != b[j]) { match[i][j] = mymax(match[i][j], match[pos_a-1][pos_b-1]+2); } } } cout <<match[a_n][b_n]<<endl; } return 0; }