http://acm.hdu.edu.cn/showproblem.php?pid=1080
题意:
给定两个字符串 s1 和 s2 ,在两个串中都可以插入空格,使两个串的长度最后相等,然后开始匹配,怎样插入空格由匹配规则得到的值最大。
状态转移方程:
dp[i][j] = Max( dp[i-1][j] + val(str1[i],'-'), dp[i][j-1] + val('-',str2[j]), dp[i-1][j-1] + val(str1[i],str2[j]) );
#include<stdio.h>
#include<string.h>
#include<map>
using namespace std;
const int maxn = 105;
int len,len1,len2;
char str1[maxn],str2[maxn];
int dp[maxn][maxn];
int table[6][6]={
0,0,0,0,0,0,
0,5,-1,-2,-1,-3,
0,-1,5,-3,-2,-4,
0,-2,-3,5,-2,-2,
0,-1,-2,-2,5,-1,
0,-3,-4,-2,-1,-1000000,
};
int Max( int a,int b,int c )
{
a = a >= b?a:b;
return a >= c?a:c;
}
int ma( char ch )
{
if( ch == 'A' )
return 1;
else if( ch == 'C' )
return 2;
else if( ch == 'G' )
return 3;
else if( ch == 'T' )
return 4;
else
return 5;
}
int val(char a,char b){
int c = ma(a); int d = ma(b);
return table[c][d];
}
void getDP()
{
memset( dp,0,sizeof(dp) );
for( int i = 1; i <= len1; i ++ )
dp[i][0] = dp[i-1][0]+val(str1[i],'-');
for( int i=1; i <= len2; i ++ )
dp[0][i] = dp[0][i-1]+val('-',str2[i]);
for( int i = 1; i <= len1; i ++ )
{
for( int j = 1; j <= len2; j ++ )
{
// str1[i]与空格匹配符 str2[i]与空格匹配 str1[i]与str2[i]匹配
dp[i][j] = Max( dp[i-1][j] + val(str1[i],'-'), dp[i][j-1] + val('-',str2[j]), dp[i-1][j-1] + val(str1[i],str2[j]) );
}
}
}
int main()
{
//freopen("data.in","r",stdin);
int t;
scanf("%d",&t);
while( t-- )
{
scanf("%d %s",&len1,str1+1);
scanf("%d %s",&len2,str2+1);
if( len1 >= len2 ) len = len1;
else len = len2;
getDP();
printf("%d\n",dp[len1][len2]);
}
return 0;
}