[Edit] Luo Gu distance

Portal original title
yourself knocked the first line of the two-dimensional DP title(Although secretly turned a bit arithmetic book)I feel very beautiful

Thinking

Provided dp [i] [j] represents the X [i] and the edit distance Y [j] of.

Then, three actions can be performed:
Insert x [i] (equivalent to deleting y [j]), then dp [i] [j] is equal to dp [i-1] [j ] +1.
Insert x [i] (equivalent to deleting y [j]), then dp [i] [j] is equal to dp [i-1] [j ] +1.
the x [i] is replaced Y J .

The use of greedy, get the state transition equation is:

dp[i][j]=min{dp[i-1][j]+1,dp[i-1][j]+1,dp[i-1][j-1]+(x[i]!=y[j])}

The rest is a mix of code, not repeat them.

Code

#include<iostream>
#include<string>
using namespace std;

string A,B;
int dp[2001][2001];

int min(int a,int b,int c)
{
    if(a<=b&&a<=c)
        return a;
    if(b<=a&&b<=c)
        return b;
    if(c<=a&&c<=b)
        return c;
}

int main()
{
    //freopen("testdata.in","r",stdin);
    cin>>A>>B;
    for(int i=1;i<=A.size();i++)
    {
        dp[i][0]=i;
    }
    for(int j=1;j<=B.size();j++)
    {
        dp[0][j]=j;
    }
    for(int i=1;i<=A.size();i++)
    {
        for(int j=1;j<=B.size();j++)
        {
            dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+(A[i-1]!=B[j-1]));
        }
    }
    /*
    生成DP表格以便调试 
    cout<<" "<<B<<endl;
    for(int i1=1;i1<=A.size();i1++)
    {    
        cout<<A[i1-1];
        for(int j1=1;j1<=B.size();j1++)
        {
            cout<<dp[i1][j1];
        }
        cout<<endl;
    }
    cout<<endl;    
    */    
    cout<<dp[A.size()][B.size()];
    return 0;
}

Guess you like

Origin www.cnblogs.com/gongkai/p/11031533.html