题解
dp[i][j]
表示 s1 的前 i 个字符和 s2 的前 j 个字符 的最大相似度。
则,
dp[i][j]=max(dp[i−1][j−1]+scoreMatrix[s1[i]][s2[j]],dp[i−1][j]+scoreMateix[s1[i]][‘−‘],dp[i][j−1]+scoreMatrix[‘−‘][s2[j]]])
初始条件:
dp[0][0] = 0
dp[i][0] = dp[i - 1][0] + scoreMatrix[s1[i]][‘-‘]
dp[0][j] = dp[0][j - 1] + scoreMatrix[‘-‘][s2[j]]
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#include <string>
#include <cstring>
using namespace std;
const int maxn = 100 + 10;
char s1[maxn], s2[maxn];
int len1, len2, t;
int dp[maxn][maxn];
int scoreMatrix[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 },
};
map<char, int> mp;
void solve()
{
memset(dp, 0, sizeof(dp));
dp[0][0] = 0;
for(int i = 1; i <= len1; ++i) {
dp[i][0] = dp[i - 1][0] + scoreMatrix[ mp[s1[i]] ][ mp['-'] ];
}
for(int i = 1; i <= len2; ++i) {
dp[0][i] = dp[0][i - 1] + scoreMatrix[ mp['-'] ][ mp[s2[i]] ];
}
for(int i = 1; i <= len1; ++i){
for(int j = 1; j <= len2; ++j){
dp[i][j] = dp[i - 1][j - 1] + scoreMatrix[ mp[s1[i]] ][ mp[s2[j]] ];
dp[i][j] = max(dp[i][j], dp[i - 1][j] + scoreMatrix[ mp[s1[i]] ][ mp['-'] ]);
dp[i][j] = max(dp[i][j], dp[i][j - 1] + scoreMatrix[ mp['-'] ][ mp[s2[j]] ]);
}
}
}
int main()
{
#ifdef LOCAL
freopen("data.in", "r", stdin);
#endif // LOCAL
mp['A'] = 0, mp['C'] = 1, mp['G'] = 2, mp['T'] = 3, mp['-'] = 4;
for(cin >> t; t--; ){
scanf("%d %s", &len1, s1 + 1);
scanf("%d %s", &len2, s2 + 1);
solve();
printf("%d\n", dp[len1][len2]);
}
return 0;
}