Title: 【POJ1080】Human Gene Functions
This question can be thought of using DP to do it at a glance.
First, put the table in the question in a function:
int s(char x,char y) { if(x=='A') { if(y=='A') return 5; if(y=='C') return -1; if(y=='G') return -2; if(y=='T') return -1; if(y=='-') return -3; } if(x=='C') { if(y=='A') return -1; if(y=='C') return 5; if(y=='G') return -3; if(y=='T') return -2; if(y=='-') return -4; } if(x=='G') { if(y=='A') return -2; if(y=='C') return -3; if(y=='G') return 5; if(y=='T') return -2; if(y=='-') return -2; } if(x=='T') { if(y=='A') return -1; if(y=='C') return -2; if(y=='G') return -2; if(y=='T') return 5; if(y=='-') return -1; } if(x=='-') { if(y=='A') return -3; if(y=='C') return -4; if(y=='G') return -2; if(y=='T') return -1; if(y=='-') return 0; } return 0; }
Then, we have to figure out a way to derive a state transition equation, which is the core part of the entire code.
We denote the maximum similarity that can be obtained when the first string (denoted as s1) matches the i-th position and the second string (denoted as s2) matches the j-th position as f[i][j] , then for f[i][j], it may be obtained from 3 ways:
①f[i][j]=f[i-1][j]+s(s1[i],'-')
②f[i][j]=f[i][j-1]+s('-',s2[j])
③f[i][j]=f[i-1][j-1]+s(s1[i],s2[j])
This should be relatively obvious, so it will not be proved or explained.
From the above, the state transition equation of this question is f[i][j]=max{ f[i-1][j]+s(s1[i],'-') , f[i][j -1]+s('-',s2[j]) , f[i-1][j-1]+s(s1[i],s2[j]) }.
Now that the state transition equation has been introduced, the rest is easy to do, just go to the code:
#include<cstdio> #include<iostream> #include<algorithm> #define N 100 using namespace std; int n,m,f[N+5][N+5]; string s1,s2; int s(char x,char y) { if(x=='A') { if(y=='A') return 5; if(y=='C') return -1; if(y=='G') return -2; if(y=='T') return -1; if(y=='-') return -3; } if(x=='C') { if(y=='A') return -1; if(y=='C') return 5; if(y=='G') return -3; if(y=='T') return -2; if(y=='-') return -4; } if(x=='G') { if(y=='A') return -2; if(y=='C') return -3; if(y=='G') return 5; if(y=='T') return -2; if(y=='-') return -2; } if(x=='T') { if(y=='A') return -1; if(y=='C') return -2; if(y=='G') return -2; if(y=='T') return 5; if(y=='-') return -1; } if(x=='-') { if(y=='A') return -3; if(y=='C') return -4; if(y=='G') return -2; if(y=='T') return -1; if(y=='-') return 0; } return 0; } intmain() { int T; scanf("%d",&T); while(T--) { scanf("%d",&n),cin>>s1,scanf("%d",&m),cin>>s2; s1="-"+s1,s2="-"+s2;//Add a '-' before s1 and s2 for(int i=1;i<=n;i++) f[i][0]=f[i-1][0]+s(s1[i],'-');//Preprocessing, next same for(int i=1;i<=m;i++) f[0][i]=f[0][i-1]+s('-',s2[i]); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) f[i][j]=max(max(f[i-1][j]+s(s1[i],'-'),f[i][j-1]+s('-',s2[j])),f[i-1][j-1]+s(s1[i],s2[j]));//DP过程 printf("%d\n",f[n][m]);//Output the answer } return 0; }
Copyright statement: Please indicate the address for reprinting