-
Question meaning: What is the least steps it takes for you changing a string to another string, provided that you can either add, delete, or change.
-
DP algorithm:
a) dp[i][j] is the least steps it take to transform the first i parts in the first string to the first j parts in the second string.
b) DP algorithm considers from the ending, so the sub-statements for dp[i][j] are dp[i-1][j-1], dp[i-1][j], and dp[i][j-1].
c) Initialization: dp[0][i]=dp[i][0]=i.
d) Function transformation equation: dp[i-1][j-1];
e) If the i character of the first string equals to the j character of the second string, then transform, else + 1.
f) dp[i-1][j] represents the number of steps it takes for deleting the i character of the first string and adding the i-1 characters to form the j element in the second string; similar with dp[i-1][j], dp[i][j-1] inserts the first string with the j character and adds the original i characters to form the j – 1 characters in the second string.
g) Find the smallest between dp[i-1][j-1] + str1[i] == str2[j] ? 1 : 0; dp[i-1][j] + 1; dp[i][j-1] + 1; -
Function transformation equation:
a) If we want to add A[i] after B[j], then at least we need dp[i][j] = dp[i-1][j] + 1 steps.
b) If we want to add B[j] after A[i], then at least we need dp[i][j] = dp[i][j-1] + 1 steps.
c) If we want to change B[j] to be A[i], we have to consider whether B[j] == A[i]
i. If B[j] == A[i], nothing changed, and we need 0 step.
ii. If B[j] != A[i], we need 1 step.
iii. Therefore, we use dp[i][j] = dp[i-1][j-1] + (A[i] == B[j]? 0 1)
d) We just need to find the minimum from the three choices above. -
Boundaries: initialize dp[0][0, …, m] dp[0, …, n][0].
-
Sample code:
#include
#include
#include
int len1,len2;
int dp[1005][1005];
char s1[1005],s2[1005];
using namespace std;
inline int min(int a,int b)
{
return a<b? a:b;
}
inline int max(int a,int b)
{
return a>b? a:b;
}
int init()
{
memset(dp,0,sizeof(dp));
int tmp=max(len1,len2);
for(int i=1;i<=tmp;++i)
{
dp[i][0]=dp[0][i]=i;
}
}
int DP()
{
for(int i=1;i<=len1;++i)
{
for(int j=1;j<=len2;++j)
{
if(s1[i]==s2[j])
dp[i+1][j+1]=min(min(dp[i+1][j]+1,dp[i][j+1]+1),dp[i][j]);
else
dp[i+1][j+1]=min(min(dp[i+1][j]+1,dp[i][j+1]+1),dp[i][j]+1);
}
}
return dp[len1][len2];
}
int main()
{
while(cin>>len1>>s1)
{
cin>>len2>>s2;
init();
cout<<DP()<<endl;
}
system(“pause”);
return 0;
}
Analysis for POJ 3356: DP algorithm
最新推荐文章于 2024-06-24 19:18:08 发布