【洛谷P1140 相似基因】动态规划
分析
f[i][j] 表示 1数组的第i位和2数组的第j位匹配的最大值
f[1][1]=-2
f[2][1]=-2+5=3
f[3][1]=-2+5+5=8
三个决策:
1、由f[i-1][j-1]直接推得
2、a[i]位匹配'-' f[i][j]=Max(f[i-1][j]+v[4][a]);
3、b[j]位匹配'-' f[i][j]=Max(f)
f[i][j]=f[i-1][j-1]+v[a[i]][b[j]]
AC代码
// luogu-judger-enable-o2
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <ctype.h>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#define lson nod<<1
#define rson nod<<1|1
#define ms(a,b) memset(a,b,sizeof(a))
#define Inf 0x7fffffff
using namespace std;
typedef long long LL;
namespace Fastio{
inline int read() {
int w=0,x=0; char ch=0;
while (!isdigit(ch)) {w|=ch=='-';ch=getchar();}
while (isdigit(ch)) {x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
return w?-x:x;
}
inline void write(int x) {
int y(10),len(1);
while (y<=x) y=(y<<1)+(y<<3),len++;
while (len--) {y/=10;putchar(x/y+48);x%=y;}
}
template <class T> T Min(T x,T y){return(x)<(y)?(x):(y);}
template <class T> T Max(T x,T y){return(x)<(y)?(y):(x);}
}
using namespace Fastio;
const int v[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}};
char ch1[105],ch2[105];
int a[105],b[105];
int f[105][105];
int n,m;
inline void Change(char s[],int a[]) {
for (int i=0;i<strlen(s);i++) {
if (s[i]=='A') a[i+1]=0;
if (s[i]=='C') a[i+1]=1;
if (s[i]=='G') a[i+1]=2;
if (s[i]=='T') a[i+1]=3;
}
}
int main() {
n=read(); scanf("%s",ch1); Change(ch1,a);
m=read(); scanf("%s",ch2); Change(ch2,b);
for (int i=1;i<=n;i++) f[i][0]=f[i-1][0]+v[4][a[i]];
for (int i=1;i<=m;i++) f[0][i]=f[0][i-1]+v[4][b[i]];
for (int i=1;i<=n;i++) {
for (int j=1;j<=m;j++) {
f[i][j]=f[i-1][j-1]+v[a[i]][b[j]];
f[i][j]=Max(f[i][j],f[i-1][j]+v[4][a[i]]);
f[i][j]=Max(f[i][j],f[i][j-1]+v[4][b[j]]);
}
}
printf("%d\n",f[n][m]);
return 0;
}
黎明的朝阳,会为苦难中最坚强的信念升起