动态规划问题
最长公共子串的变形 主要注意初始化
#include<iostream> using namespace std; #define N 105 int v[N][N],dp[N][N]; char s1[N],s2[N]; int max(int a,int b) { return a>b?a:b; } void init() { v['A']['A']=5; v['C']['C']=5; v['G']['G']=5; v['T']['T']=5; v['A']['C']=-1; v['A']['G']=-2; v['A']['T']=-1; v['A']['-']=-3; v['C']['A']=-1; v['C']['G']=-3; v['C']['T']=-2; v['C']['-']=-4; v['G']['A']=-2; v['G']['C']=-3; v['G']['T']=-2; v['G']['-']=-2; v['T']['A']=-1; v['T']['C']=-2; v['T']['G']=-2; v['T']['-']=-1; v['-']['A']=-3; v['-']['C']=-4; v['-']['G']=-2; v['-']['T']=-1; } int main() { int la,lb,t,i,j; cin>>t; init(); while(t--) { cin>>la>>s1; cin>>lb>>s2; for(i=1;i<=la;i++)dp[0][i]=dp[0][i-1]+v['-'][s2[i-1]]; //dp[i][j]表示s1前i个字符 s2前j个字符时 最大的相似度 dp[i][0]表示s1前i个与s2都不符合 for(i=1;i<=lb;i++)dp[i][0]=dp[i-1][0]+v[s1[i-1]]['-'];
for(i=1;i<=la;i++) for(j=1;j<=lb;j++) { dp[i][j]=max(max(dp[i-1][j]+v[s1[i-1]]['-'],dp[i][j-1]+v['-'][s2[j-1]]),dp[i-1][j-1]+v[s1[i-1]][s2[j-1]]); } cout<<dp[la][lb]<<endl; } return 0; }