Dynamic programming
mit course thinking:
optimization of lcs problem:
1. Compress the space complexity to On as follows
#include<iostream>
#include<cstdio>
using namespace std;
int a[100005];
int b[100005];
int dp[2][100005];
int read()
{
int x=0;
char ch=getchar();
while(ch<'0'||ch>'9')
{
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=getchar();
}
return x;
}
int main()
{
//freopen("in.txt","r",stdin);
int n=read();
for(int i=1;i<=n;i++)
{
a[i]=read();
}
for(int i=1;i<=n;i++)
{
b[i]=read();
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i]==b[j])
{
dp[i&1][j]=dp[(i-1)&1][j-1]+1;//奇偶优化,对于dp数组而言,其第一维存储的i可以压缩至i&1(奇偶)的种类数(2),而不影响结果
}
else
{
dp[i&1][j]=max(dp[(i-1)&1][j],dp[i&1][j-1]);
}
}
}
printf("%d",dp[n&1][n]);
return 0;
}
2. Save path
Save the path in min(n,m) space
Edit distance problem
Let A and B be 2 strings. Convert string A to string B with minimal character manipulation. The character operations mentioned here include (1) delete a character; (2) insert a character; (3) change a character to another character. The minimum number of character operands used to transform string A into string B is called the edit distance from string A to B, denoted as d(A, B). For the given string A and string B, calculate the edit distance d(A,B).