【题解】小好吃说鬼话
题目
小好吃经常说一些奇奇怪怪的话。为了衡量小好吃的正常程度,03决定计算小好吃说的两句话的编辑距离。两个字符串的编辑距离定义为:最少进行多少次插入一个字符/删除一个字符/改变一个字符的操作,能将一个串变为另一个。如果答案大于50,03认为小好吃无药可救。此时请输出-1
输入格式
两行两个小写字母组成的字符串,表示小好吃的两句话。
输出格式
输出一行一个整数,表示两个字符串的编辑距离。如果答案大于50,请输出-1.
样例输入
zhoudafu
zhouliufu
样例输出
3
题解
对于这道题我们考虑dp
设dp[i][j]表示对于a串前i位和b串前j位的编辑距离
则有dp[i][j] = min(dp[i][j],dp[i][j-1]+1,dp[i-1][j]+1,dp[i-1][j-1] + (a[i] == b[j]))
但数据范围过大,无法全部储存
我们考虑只储存对每个a串中的字符前后50位有效数据储存
dp[i][j] = f[i][j - i + 50]
记忆化搜索即可
#include<bits/stdc++.h>
using namespace std;
inline int Read(){
int s = 0 , w = 1;
char ch = getchar();
while(ch > '9' && ch < '0'){
if(ch == '-') w = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
s = (s << 1) + (s << 3) + ch - '0';
ch = getchar();
}
return s * w;
}
const int MAXN = 500 + 50;
int f[MAXN][MAXN];
string s1,s2;
int DP(int s,int t){
if(min(s,t) == 0) return max(s,t);
if(f[s][t]) return f[s][t];
int res = 19260817ll;
if(s1[s] == s2[t]) res = min(res,DP(s-1,t-1));
else res = min(res,DP(s-1,t-1) + 1);
res = min(res,DP(s-1,t) + 1);
res = min(res,DP(s,t-1) + 1);
return (f[s][t] = res);
}
int main(){
cin >> s1 >> s2;
s1 = "s" + s1;
s2 = "s" + s2;
int ans = DP(s1.size(),s2.size());
cout << ans << endl;
return 0;
}