洛谷:P2758 编辑距离(dp,普及/提高-)

题目:

在这里插入图片描述

分析:和最长公共子序列一样倒着来。即可。

代码:

#include<bits/stdc++.h>
using namespace std;
long long A[2001][2001];
string s1,s2;
long long f(int x,int y)
{
 if(x==-1&&y==-1) {
  return 0;
 }
 if(x==-1)
 {
  return y+1;
 }
 if(y==-1)
 {
  return x+1;
 }
 if(A[x][y]!=1<<30) return A[x][y];
 if(s1[x]==s2[y]) A[x][y]=f(x-1,y-1);
 else{
 A[x][y]=min(f(x-1,y)+1,f(x,y-1)+1);
 A[x][y]=min(A[x][y],f(x-1,y-1)+1); 
 }
 return A[x][y]; 
}
int main()
{
 for(int i=0;i<2001;i++)
 for(int j=0;j<2001;j++) A[i][j]=1<<30;
 cin>>s1;
 cin>>s2;
 cout<<f(s1.size()-1,s2.size()-1);
}

猜你喜欢

转载自blog.csdn.net/weixin_42721412/article/details/107550613