UVA 526 Solution - String Distance and Transform Process
/* Solved by using Edit-Distance Algorithm*/
/*UVA id: shoaib05
Accepted Time: 0.103
*/
#include<iostream>
#include<string.h>
#include<algorithm>
#include<cstdio>
using namespace std;
char x[90],y[90];
int len1,len2,table[90][90];
void buildTable()
{
int i,j;
for(i=0;i<=len1;i++)
table[i][0]=i;
for(j=0;j<=len2;j++)
table[0][j]=j;
for(i=1;i<=len1;i++)
{
for(j=1;j<=len2;j++)
{
if(x[i-1]==y[j-1])
table[i][j]=table[i-1][j-1];
else
table[i][j]=min(table[i-1][j-1],min(table[i-1][j],table[i][j-1]))+1;
}
}
}
void result()
{
int i=len1,j=len2;
int cnt=1;
cout<<table[i][j]<<endl;
while(i || j)
{
if(i>0 && y>0 &&(x[i-1]==y[j-1]))
{
i--;
j--;
continue;
}
if(i>0 && (table[i-1][j]+1==table[i][j]))
{
cout<<cnt++<<" Delete "<<i<<endl;
i--;
}
else if(i>0 && j>0 && (table[i][j]==table[i-1][j-1]+1))
{
cout<<cnt++<<" Replace "<<i<<","<<y[j-1]<<endl;
i--;
j--;
}
else if(j>0)
{
cout<<cnt++<<" Insert "<<i+1<<","<<y[j-1]<<endl;
j--;
}
}
}
int main()
{
bool flag=false;
while(gets(x))
{
gets(y);
len1=strlen(x);
len2=strlen(y);
if(flag)
cout<<endl;
flag=true;
buildTable();
result();
}
return 0;
}
Comments
Post a Comment