http://poj.org/problem?id=1080
discuss 里面的解释已经很经典很明白了。http://poj.org/showmessage?message_id=74842
#include <cstdio> #include <cstring> #include <iostream> #define maxn 107 using namespace std; int f[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 dp[maxn][maxn]; char st1[maxn],st2[maxn]; char tmp[5] = {'A','C','G','T','-'}; int getnum(char s) { for (int i = 0; i < 5; ++i) { if (s == tmp[i]) return i; } return -1; } int main() { //freopen("in.txt","r",stdin); int i,j,t,l1,l2; scanf("%d",&t); while (t--) { scanf("%d%s",&l1,st1 + 1); scanf("%d%s",&l2,st2 +1); /* char ch[2]; scanf("%s",ch); printf("%d\n",getnum(ch[0]));*/ dp[0][0] = 0; memset(dp,0,sizeof(dp)); for (i = 1; i <= l1; ++i) { int pos = getnum(st1[i]); //printf("<<<<>>%d\n",pos); dp[i][0] = dp[i - 1][0] + f[pos][4]; } for (i = 1; i <= l2; ++i) { int pos = getnum(st2[i]); //printf("||<<<<>>%d\n",pos); dp[0][i] = dp[0][i - 1] + f[4][pos]; } for (i = 1; i <= l1; ++i) { for (j = 1; j <= l2; ++j) { int x = getnum(st1[i]); int y = getnum(st2[j]); if (st1[i] == st2[j]) { dp[i][j] = dp[i - 1][j - 1] + f[x][y]; } else { dp[i][j] = max(max(dp[i - 1][j] + f[x][4],dp[i][j -1] + f[4][y]),dp[i - 1][j - 1] + f[x][y]); } } } printf("%d\n",dp[l1][l2]); } return 0; }