POJ 1080 Human Gene Functions(LCS变形)

题目链接

题目大意

  给两个不同的字符串,比较其相似度,你可以在字符之间插入'-',不同字符之间的相似度参考题目中的表格。

解题思路

  这题主要还是考验对LCS的理解。定义dp[i][j]表示第一个串s1长度为i时与第二个串s2长度为j时的相似度(注意不算'-')。
  我们在求dp[i][j]的时候,分三种情况:
  1.s1[i]与s2[j]相匹配,那么结果就是直接长度为i-1的串s1与长度为j-1的串s2的匹配结果加上这两个字符的匹配度。
  2.如果s1[i]与s2[j]之前的某个字符匹配了,那么s2[j]就只能和'-'匹配了。
  3.如果s1[i]之前的某个字符与s2[j]的某个字符匹配了,那么s1[i]就只能和'-'匹配了。
  dp的状态转移方程与LCS相似,注意dp[i][0]与dp[0][j]的初值,具体看代码吧。

代码

const int maxn = 1e2+10;
const int maxm = 2e2+10;
int l1, l2, dp[maxn][maxn], mp[maxn][maxn], skp[maxn]; 
char s1[maxn], s2[maxn];
int main() {
    mp['A']['A'] = mp['C']['C'] = mp['G']['G'] = mp['T']['T'] = 5;
    mp['A']['C'] = mp['C']['A'] = -1;
    mp['A']['G'] = mp['G']['A'] = -2;
    mp['A']['T'] = mp['T']['A'] = -1;
    mp['C']['G'] = mp['G']['C'] = -3;
    mp['C']['T'] = mp['T']['C'] = -2;
    mp['G']['T'] = mp['T']['G'] = -2;
    skp['A'] = -3; skp['C'] = -4, skp['G'] = -2, skp['T'] = -1;
    int t; cin >> t;
    while(t--) {
        cin >> l1 >> (s1+1) >> l2 >> (s2+1);
        for (int i = 1; i<=l1; ++i) dp[i][0] = dp[i-1][0]+skp[s1[i]];
        for (int i = 1; i<=l2; ++i) dp[0][i] = dp[0][i-1]+skp[s2[i]];
        for (int i = 1; i<=l1; ++i)
            for (int j = 1; j<=l2; ++j)
                dp[i][j] = max(dp[i-1][j-1]+mp[s1[i]][s2[j]], 
                max(dp[i-1][j]+skp[s1[i]], dp[i][j-1]+skp[s2[j]]));
        cout << dp[l1][l2] << endl;
    }
    return 0;
}
posted @ 2020-08-26 15:48  shuitiangong  阅读(103)  评论(0编辑  收藏  举报