VJ_String Distance and Transform Process _dp+string

String Distance and Transform Process

//
//#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

const int N=111;
char s1[N],s2[N];
int dp[N][N],f[N][N];   

int main()
{
    int i,j,k,len1,len2,pos1,pos2,tt,cnt;

    while( cin>>s1>>s2 )
    {
        len1=strlen(s1);
        len2=strlen(s2);
        for( i=0;i<N;++i )                  // f[]
            for( j=0;j<N;++j )
                f[i][j]=!( s1[i]==s2[j] );  // 相等就没必要变
        for( i=0;i<N;++i )
            dp[0][i]=dp[i][0]=i;            // +n次 -n次
        for( i=1;i<=len1;++i )              // dp
            for( j=1;j<=len2;++j )  								// +1
                dp[i][j]=min( dp[i-1][j-1]+f[i-1][j-1],min( dp[i-1][j]+1,dp[i][j-1]+1 ) );
                            // 替换 1                       // 添加 2   // 删除 3
        cout<<dp[len1][len2]<<endl;

        pos1=len1; pos2=len2; cnt=1;
        while( cnt<=dp[len1][len2] )
        {
            if( pos1==0 && pos2 )       tt=2;
            else if( pos1 && pos2==0 )  tt=3;
            else if( pos1 && pos2 )
            {
                // error. dp 状态转移方程 是 min( x,min( y,z ) ) 
                // tt=dp[pos1][pos2];
                // if( tt==dp[pos1-1][pos2]+1 )    tt=2;
                // if( tt==dp[pos1][pos2-1]+1 )  	tt=3;
                // else tt=!( dp[pos1][pos2]==dp[pos1-1][pos2-1] );
                
                tt=min( dp[pos1-1][pos2-1],min( dp[pos1][pos2-1],dp[pos1-1][pos2] ) );

                // if( dp[pos1][pos2-1]==tt ) tt=2;
                // if( dp[pos1-1][pos2]==tt ) tt=3;
                // if( dp[pos1-1][pos2-1]==tt ) tt=!( dp[pos1][pos2]==dp[pos1-1][pos2-1] );
                
                // 替换一步到位 优先考虑替换 
                if( dp[pos1-1][pos2-1]==tt ) 
                    tt=!( dp[pos1][pos2]==dp[pos1-1][pos2-1] );
                else if( dp[pos1][pos2-1]==tt ) tt=2;
                else if( dp[pos1-1][pos2]==tt ) tt=3;
            }
            switch(tt)                          // pos1-- because pos1 is num not pos 
            {                                   // --pos2 num->pos
                case 0: --pos1; --pos2; break;
                case 1: cout<<cnt++<<" Replace "<<pos1--<<","<<s2[--pos2]<<endl; break;
                case 2: cout<<cnt++<<" Insert "<<pos1+1<<","<<s2[--pos2]<<endl; break;
                case 3: cout<<cnt++<<" Delete "<<pos1--<<endl; break;
            }
        }                                       // pos1-- vs pos1+1
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_63173957/article/details/124185979
今日推荐