Edit Distance Problem

/* ==========  ========== ========== ========= ======== ===========*/
//            CF - Edit Distance Problem                                                                               //
//       Solution Code using  DP                                     //
//            Author - Piyush Jain                                                                                            //
//                                                                                                                                         //
/* ========== ========== ========== ==========  ========== ======   */

//Note:- We are converting  string s into t and assuming and every operaion (INSERT,DELETE and REPLACEMENT took ONE unit cost)
// dp[i-1][j] => stand for insert operation in "s" string
// dp[i][j-1] => stand for delete operation in "s" string
// dp[i-1][j-1] => replacement of i-1th character in "s" string via j-1th character of string "t".
 // and take minimum of these three operation. and store in dp[i][j]  


#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <climits>
#include <queue>
#include <set>
#include <list>
#include <map>
#include <cmath>
#include <stack>
#include <queue>

using namespace std;
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define FOREQ(i,a,b) for(int i=a;i<=b;i++)
#define RFOR(i,a,b) for(int i=b-1;i>=0;i--)
#define REQFOR(i,a,b) for(int i=b;i>=0;i--)
#define MAX 10000003
#define LMAX 1000000001
typedef long long int LL;
typedef  long int L;
typedef unsigned long long int ULL;
#define PB push_back
#define F first
#define S second
int dp[1005][1004];
pair<int,char>p;
pair<string,pair<int,char> >pp;
stack<pair<string,pair<int,char> > > sta;
// stack<pair<string,pair<int,char> > > > :: iterator it;

int main()
{
    string s,t;
    cin>>s>>t;
    int m = s.length();
    int n = t.length();
 

    FOR(i,0,m+1)
    {
        FOR(j,0,n+1)
        {
            if(i == 0)
                dp[i][j] = j; // IF s string has 0 length
            else if(j == 0)
                dp[i][j] = i; // IF t string has 0 length
            else if(s[i-1] == t[j-1])
                dp[i][j] = dp[i-1][j-1]; //if same character is same
            else
                dp[i][j] = min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1;  
        }                                                                    
    }                                                                      
    cout<<dp[m][n]<<endl;                                                  
}

Comments

Popular posts from this blog

Enable logging in Haproxy.

Take AWS ec2 volume instance snapshot