Its a question on minimum distance or the minimum steps required to convert a given String to another String.The Only addition step here is that we can swap 2 variables.
Here is the Link Of the question:CodeChef: Practical coding for everyone
Now this can be solved by DP.In the case of swap I have used an additional step which is in my solution
#include<stdio.h>
#include<string.h>
#define LARGE 100000
int T[101][101];
char a[101];
char b[101];
int MIN(int a, int b) {
return a < b ? a : b;
}
int min(int a,int b,int c){
return MIN(MIN(a, b), c);
}
void dispaly(int m,int n){
int i,j;
for(i=0;i<=m;i++){
for(j=0;j<=n;j++)
printf("%d ",T[i][j]);
printf("\n");
}
}
int minChange(char *a,char *b,int m,int n){
int i=0,j=0,u,v,w,x,a1,b1=LARGE;
char t;
for(j=0;j<=n;j++){
T[0][j]=j;
}
for(i=0;i<=m;i++){
T[i][0]=i;
}
//dispaly(m,n);
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
u=T[i-1][j]+1;
v=T[i][j-1]+1;
w=T[i-1][j-1]+(a[i-1]!=b[j-1]);
a1=min(u,v,w);
//The case Of swapping is checked
if(j>=2){
if(a[i-1]==b[j-2]&& a[i-2]==b[j-1])
b1=T[i-2][j-2]+1;
}
a1=MIN(a1,b1);
T[i][j]=a1;
}
b1=LARGE;
}
return T[m][n];
}
int main(){
int t=0,l1,l2;
scanf(“%d”,&t);
while(t-- > 0){
scanf("%s%s",a,b);
l1=strlen(a);
l2=strlen(b);
printf("%d\n",minChange(a,b,l1,l2));
}
//getch();
return 0;
}
The question is similar to the:Edit Distance | DP-5 - GeeksforGeeks
only the the addition step in the question is of swapping
I am getting wrong ans plz help