題意:是求最長公共子序列的一個變型題;此題中的字符只有A,G,C,T四個,再加上'-';它們之間的不同匹配有對應的不同權值W;而且只有字符相同的匹配的權值為大於0;其他都為負值。此題就是求權值最大的匹配。
f[i][j]: 表示第一個字符串的前 i 個字符和第二個字符串的前 j 個字符的最大權值。
狀態方程:
f[i][j]=max(f[i-1][j]+w[a[i]]['-'],f[i][j-1]+w['-'][b[j]],f[i-1][j-1]+w[a[i]][b[j]]);
// Time 16ms; Memory 324K
#include<iostream> using namespace std; int max(int a,int b,int c) { a=a>b?a:b; return a>c?a:c; } int main() { int i,j,t,n,m,f[110][110],w['T'+1]['T'+1];//權值 char a[110],b[110]; w['A']['A']=5; w['C']['C']=5; w['G']['G']=5; w['T']['T']=5; w['A']['C']=w['C']['A']=-1; w['A']['G']=w['G']['A']=-2; w['A']['T']=w['T']['A']=-1; w['A']['-']=w['-']['A']=-3; w['C']['G']=w['G']['C']=-3; w['C']['T']=w['T']['C']=-2; w['C']['-']=w['-']['C']=-4; w['G']['T']=w['T']['G']=-2; w['G']['-']=w['-']['G']=-2; w['T']['-']=w['-']['T']=-1; cin>>t; while(t--) { cin>>n>>a; cin>>m>>b; f[0][0]=0; for(i=1;i<=n;i++) f[i][0]=f[i-1][0]+w[a[i-1]]['-'];//初始化 for(j=1;j<=m;j++) f[0][j]=f[0][j-1]+w['-'][b[j-1]]; for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { f[i][j]=max(f[i-1][j]+w[a[i-1]]['-'],f[i][j-1]+w['-'][b[j-1]],f[i-1][j-1]+w[a[i-1]][b[j-1]]); } } cout<<f[n][m]<<endl; } return 0; }