UVA 429 Solution - Word Transformation

UVA 429 Solution - Word Transformation


uva id: shoaib05
Accepted Time: 0.036

I used Edit_Distance and Floyd warshall algorithm.
Every word acts as a node. Two nodes are adjacent if their edit distance is One.

map, may ,mad are adjacent of each other. But pad and map are not adjacent because their edit distance is 2. But mad and pad are adjacent because their edit distance is 1.



Here has no link between may and pad, no link between map and pad.

Code:

#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<stdio.h>
#define COLUMN 210
#define INFINITE 100000
using namespace std;
int editDistance(string str1,string str2)
{
int table[11][11],length1,length2,i,j;
length1=str1.size();
length2=str2.size();
for(i=0;i<=length1;i++)
table[0][i]=i;
for(i=1;i<=length2;i++)
table[i][0]=i;
for(i=1;i<=length2;i++)
{
for(j=1;j<=length1;j++)
{
if(str2[i-1]==str1[j-1])
table[i][j]=table[i-1][j-1];
else
table[i][j]=min(table[i-1][j-1],min(table[i][j-1],table[i-1][j]))+1;
}
}
return table[length2][length1];
}
void floyd_warsall(int (*graph)[COLUMN],int row)
{
int i,j,k;
for(i=0;i<row;i++)
{
for(j=0;j<row;j++)
{
if(i!=j && graph[i][j]!=INFINITE)
{
for(k=0;k<row;k++)
{
if(j!=k && graph[i][k]!=INFINITE)
{
graph[j][k]=min(graph[j][k],graph[i][j]+graph[i][k]);
}
}
}
}
}
}
int main() 
{
map<string,int> mymap;
map<string,int>::iterator mit1,mit2;
int i,j,test_case,graph[COLUMN][COLUMN],len,node;
string str,str1,str2;
cin>>test_case;
while(test_case--)
{
mymap.clear();
node=0;
while(cin>>str)
{
if(str[0]=='*')
break;
mymap[str]=node++;
}
for(i=0;i<node;i++)
{
for(j=0;j<node;j++)
{
if(i==j)
graph[i][j]=0;
else
graph[i][j]=INFINITE;
}
}
for(mit1=mymap.begin();mit1!=mymap.end();mit1++)
{
for(mit2=mymap.begin();mit2!=mymap.end();mit2++)
{
if(mit1!=mit2)
{
if(editDistance(mit1->first,mit2->first)>1)
graph[mit2->second][mit1->second]=graph[mit1->second][mit2->second]=INFINITE;
else
graph[mit2->second][mit1->second]=graph[mit1->second][mit2->second]=1;
}
}
}
floyd_warsall(graph,node);
getchar();
while(getline(cin,str))
{
len=str.size();
if(len==0)
break;
i=0;
while(str[i]!=' ')
i++;
str1=str.substr(0,i);
str2=str.substr(i+1,len-i-1);
cout<<str1<<" "<<str2<<" "<<graph[mymap[str1]][mymap[str2]]<<endl;
}
if(test_case>0)
cout<<endl;
}
return 0;
}

Comments

  1. sir,the consept is not clear to me..
    can you explain the logic by another example??

    ReplyDelete

Post a Comment

Popular posts from this blog

uva 679 - Dropping Balls Solution

uva 481 - What Goes Up Solution

uva-10077 Solution --- The Stern-Brocot Number System