HourRank 11 之 LCS Returns

Given two strings, and , find and print the total number of ways to insert a character at any position in stringsuch that the length of the Longest Common Subsequence of characters in the two strings increases by one.

Input Format

The first line contains a single string denoting .
The second line contains a single string denoting .

Constraints

Scoring


  • Strings and are alphanumeric (i.e., consisting of arabic digits and/or upper and lower case English letters).
  • The new character being inserted must also be alphanumeric (i.e., a digit or upper/lower case English letter).

Subtask

  • forof the maximum score.

Output Format

Print a single integer denoting the total number of ways to insert a character into stringin such a way that the length of the longest common subsequence of and increases by one.

Sample Input

aa
baaa

Sample Output

4

我确实菜啊,看了别人的代码想了n久才想出来。其实就是一道稍微难点的LCS题而已。废话不说,直入主题!

首先,同时对两边分别dp(从前往后,从后往前),我们认为分别是dp1,dp2;

我们往a中插入元素c,使得a,b的LCS增多1,那么c必定属于b嘛,对不对!

假设我们已经求出了a,b的最长子序列长度LCS

如果dp1[i][j-1]+dp2[i+1][j+1]==LCS,那么我们就认为b[j]是可以插入到a的某个位置的,具体哪个位置呢?我们令d1=dp1[i][j-1],那么插入位置就是d1+1了。

为什么这样??先假设a的长度为lena,b的长度为lenb,


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <cstring>
#include <map>
#include <set>

#define LL long long
#define pb push_back
#define pf push_front
#define loop(a,b,c) for(int a=b;a<=c;a++)
#define rloop(a,b,c) for(int a=b;a>=c;a--)
#define clr(a,b) memset(a,b,sizeof a)
#define inf 1<<30
#define x first
#define y second
#define maxn 5005

using namespace std;
int dp1[maxn][maxn],dp2[maxn][maxn];
int main()
{
	//freopen("data.txt","r",stdin);
	char a[5005],b[5005];
	int num = 0;
	cin>>a+1>>b+1;
	int lena = strlen(a+1);
	int lenb = strlen(b+1);
	loop(i,1,lena)
	{
		loop(j,1,lenb)
		{
			if(a[i]==b[j])
			dp1[i][j] = max(dp1[i-1][j-1]+1,dp1[i][j]);
			else
            dp1[i][j] = max(dp1[i-1][j],dp1[i][j-1]);
		}
	}
	rloop(i,lena,1)
	{
		rloop(j,lenb,1)
		{
			if(a[i]==b[j]) 
				dp2[i][j] = max(dp2[i+1][j+1]+1,dp2[i][j]);
			else
				dp2[i][j] = max(dp2[i+1][j],dp2[i][j+1]);
		}
	}
	int lcs = dp1[lena][lenb],ans = 0;
	set<char> f;
	loop(i,0,lena)
	{
		loop(j,1,lenb)
		{
			if(dp1[i][j-1]+dp2[i+1][j+1]==lcs)
			{
				if(!f.count(b[j]))
				{
					ans++;
					f.insert(b[j]);
				}
			}
		}
		f.clear();
	}
	cout<<ans<<endl;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值