这题是dp中的最长公共子列的问题。
#include <iostream>
#include <limits>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
using namespace std;
int const size = 1000 + 10;
int a[size] , b[size];
int d[size][size];
int dp(int x , int y)
{
if(d[x][y] >= 0) return d[x][y];
if(a[x] == b[y]) return d[x][y] = dp(x-1 , y-1) + 1;
else return d[x][y] = max(dp(x , y-1) , dp(x-1 , y));
}
int main()
{
int m , n , cnt = 0;
while(scanf("%d%d" , &m , &n) == 2 && m && n)
{
for(int i = 1 ; i <= m ; ++i) scanf("%d" , a + i);
for(int i = 1 ; i <= n ; ++i) scanf("%d" , b + i);
memset(d , -1 , sizeof(d));
for(int i = 0 ; i < size ; ++i) d[i][0] = d[0][i] = 0;
printf("Twin Towers #%d\n" , ++cnt);
printf("Number of Tiles : %d\n\n" , dp(m , n));
}
return 0;
}