Given two strings, and , find and print the total number of ways to insert a character at any position in string such that the length of the Longest Common Subsequence of characters in the two strings increases by one.
题意就是给两个字符串a和b,a和b的lcs为k,问有几种方式往a插入一个字符使a和b的lcs为k+1…
a,b长度<=5000
样例
aa (a串)
baaa
输出 4
Explanation:
The longest common subsequence shared “a=aa”by and “b=baaa” is aa, which has a length of 2. There are two ways that the length of the longest common subsequence can be increased 3 to by adding a single character to a:
There are 3 different positions in string a where we could insert an additional ‘a’ to create longest common subsequence aaa (i.e., at the beginning, middle, and end of the string).
We can insert a ‘b’ at the beginning of the string for a new longest common subsequence of baa.
As we have 3+1=4 ways to insert an alphanumeric character into and increase the length of the longest common subsequence by one, we print 4 on a new line.
看了题解加代码=_=
一直打机有点颓,所以代码也是复制的…
思路:
要增加LCS(A,B),
那假设在A的第i个位置插入一个字符,这个字符对应的是B的第j个字符
设dp1[i][j]为i在A的1-i和B的1-j中的LCS
dp2[i][j]为i在A的i-n和B的j-m中的LCS
n为A的长度,m为B的长度
那么则有
dp1[i][j]+dp2[i+1][j+2]+1=dp1[n][m]+1;
A(1,i)+c+A(i+1,n)对应
B(1,j)+c+B(j+2,m)
复杂度n*m
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define MM(a,x) memset(a,x,sizeof(a));
#define mp make_pair
#define pb push_back
#define x first
#define y second
const LL linf = 0x3f3f3f3f3f3f3f3fLL;
const int inf = 0x3f3f3f3f;
const int mod = int(1e9) + 7;
const int N = 5010;
string A, B;
int dp1[N][N];
int dp2[N][N];
string charset;
int main()
{
freopen("in.txt","r",stdin);
cin>>A>>B;
int n = A.size(), m = B.size();
for(int i = 1; i <= n; i++)//数组从0开始
for(int j = 1; j <= m; j++)
{
if(A[i - 1] == B[j - 1]) dp1[i][j] = dp1[i - 1][j - 1] + 1;
else dp1[i][j] = max(dp1[i - 1][j], dp1[i][j - 1]);
//cout<<i<<" "<<j<<" "<<dp1[i][j]<<endl;
}
for(int i = n; i >= 1; i--)
for(int j = m; j >= 1; j--)
{
if(A[i - 1] == B[j - 1]) dp2[i][j] = dp2[i + 1][j + 1] + 1;
else dp2[i][j] = max(dp2[i + 1][j], dp2[i][j + 1]);
}
for(char c = 'a'; c <= 'z'; c++) charset.pb(c);
for(char c = 'A'; c <= 'Z'; c++) charset.pb(c);
for(char c = '0'; c <= '9'; c++) charset.pb(c);
int LCS = dp1[n][m];
int res = 0;
int v[256] = {};
for(int i = 0; i <= n; i++)//表示在A的第i个位置插入
{
MM(v, 0);
for(int j = 0; j < m; j++)//插入B[j]这个字符
{
if(dp1[i][j] + dp2[i + 1][j + 2] + 1 == LCS + 1)
{
//cout<<i<<" "<<j<<endl;
v[B[j]]=1;//这里的B[j]代表长度在j+1的地方
//说明第i个位置能插入B[j]这个字符
}
}
for(int j = 0; j < 256; j++) if(v[j]) res++;
}
cout << res << endl;
return 0;
}