这题一开始写成了先算出LCS长度,然后往回跑,把公共子串剔除,然后算值,最后发现这样做答案就固定了= =,无法求出最大值了。
后来看到题解,恍然大悟,发现自己实在太蠢了,这题三种选择,对应字符匹配,上字符对应-,下字符对应-,然后LCS框架上去了就可以了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int maxn=100+10;
char s1[maxn],s2[maxn];
int dp[maxn][maxn];
int ex[5][5]={
5,-1,-2,-1,-3,
-1,5,-3,-2,-4,
-2,-3,5,-2,-2,
-1,-2,-2,5,-1,
-3,-4,-2,-1,0
};
int main()
{
map<char,int> hash;
hash['A']=0;hash['C']=1;hash['G']=2;hash['T']=3;hash['-']=4;
int t,n,m;
scanf("%d",&t);
while(t--)
{
scanf("%d%s",&n,s1+1);
scanf("%d%s",&m,s2+1);
memset(dp,0,sizeof(dp));
for(int i=1;i<=max(n,m);i++)
{
dp[0][i]=dp[0][i-1]+ex[hash['-']][hash[s2[i]]];
dp[i][0]=dp[i-1][0]+ex[hash[s1[i]]][hash['-']];
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
int w1=ex[hash[s1[i]]][hash[s2[j]]];
int w2=ex[hash[s1[i]]][hash['-']];
int w3=ex[hash['-']][hash[s2[j]]];
dp[i][j]=max(dp[i-1][j-1]+w1,max(dp[i-1][j]+w2,dp[i][j-1]+w3));
}
}
cout<<dp[n][m]<<endl;
}
return 0;
}