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;
}