hdu 1080(LCS变形)

解题思路:这道题最开始看错题了,以为只能给长度小的那个字符串添加'-',就往“编辑距离”这个模型去想。其实这里是两个串都可以添加'-',所以模型一下子就简化了。这里可以用LCS的思路去做。

dp[i][j]表示两个串分别是前i个和前j个的最大价值。

dp[i][j] = max(dp[i-1][j-1] + score[A[i]][B[j]],max(dp[i-1][j] + score[A[i]][-], dp[i][j-1] + score[-][B[j]])),这里一定要注意不要犯这样的错误:i和j的字符相等,就想当然的认为它是从dp[i-1][j-1]转移过来的,实际上可能还会有别的匹配方式。这里老是犯错,所以一定要记住。

另外这里初始化也是要注意的地方。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int maxn = 105;
int n,m,dp[maxn][maxn],score[90][90];
char A[maxn],B[maxn];

int main()
{
	int t;
	char tmp[maxn];
	scanf("%d",&t);
	score['A']['A'] = score['C']['C'] = score['G']['G'] = score['T']['T'] = 5;
	score['A']['C'] = score['C']['A'] = -1;
	score['G']['A'] = score['A']['G'] = -2; score['G']['C'] = score['C']['G'] = -3;
	score['T']['A'] = score['A']['T'] = -1; score['T']['C'] = score['C']['T'] = -2; score['T']['G'] = score['G']['T'] = -2;
	score[' ']['A'] = score['A'][' '] = -3; score[' ']['C'] = score['C'][' '] = -4; score[' ']['T'] = score['T'][' '] = -1; score[' ']['G'] = score['G'][' '] = -2;
	while(t--)
	{
		cin >> n;
		cin >> A+1;
		cin >> m;
		cin >> B+1;
		memset(dp,0,sizeof(dp));
		for(int i = 1; i <= n; i++)
			dp[i][0] = dp[i-1][0] + score[A[i]][' '];
		for(int i = 1; i <= m; i++)
			dp[0][i] = dp[0][i-1] + score[' '][B[i]];
		for(int i = 1; i <= n; i++)
			for(int j = 1; j <= m; j++)
			{
				dp[i][j] = max(dp[i-1][j-1] + score[A[i]][B[j]],max(dp[i-1][j] + score[A[i]][' '], dp[i][j-1] + score[' '][B[j]]));
			}
		cout << dp[n][m] << endl;
	}
	return 0;
}


你可能感兴趣的:(dp)