/* Steven Skiena Compute String Edit Distance March 26, 2002 */ #define TRUE 1 #define FALSE 0 typedef int bool; #define MAXLEN 101 /* longest possible string */ #define MATCH 0 /* enumerated type symbol for match */ #define INSERT 1 /* enumerated type symbol for insert */ #define DELETE 2 /* enumerated type symbol for delete */ typedef struct { int cost; /* cost of reaching this cell */ int parent; /* parent cell */ } cell; #include cell m[MAXLEN][MAXLEN]; /* dynamic programming table */ /******************************************************************/ /* For normal edit distance computation */ goal_cell(char *s, char *t, int *i, int *j) { *i = strlen(s) - 1; *j = strlen(t) - 1; } int match(char c, char d) { if (c == d) return(0); else return(1); } int indel(char c) { return(1); } row_init(int i) /* what is m[0][i]? */ { m[0][i].cost = i; if (i>0) m[0][i].parent = INSERT; else m[0][i].parent = -1; } column_init(int i) /* what is m[i][0]? */ { m[i][0].cost = i; if (i>0) m[i][0].parent = DELETE; else m[0][i].parent = -1; } /**********************************************************************/ match_out(char *s, char *t, int i, int j) { if (s[i] == t[j]) printf("M"); else printf("S"); } insert_out(char *t, int j) { printf("I"); } delete_out(char *s, int i) { printf("D"); } /**********************************************************************/ main(){ int i,j; char s[MAXLEN],t[MAXLEN]; /* input strings */ s[0] = t[0] = ' '; scanf("%s",&(s[1])); scanf("%s",&(t[1])); printf("matching cost = %d \n", string_compare(s,t, strlen(s)-1,strlen(t)-1)); print_matrix(s,t,TRUE); printf("\n"); print_matrix(s,t,FALSE); goal_cell(s,t,&i,&j); printf("%d %d\n",i,j); reconstruct_path(s,t,i,j); printf("\n"); } /**********************************************************************/ int string_compare(char *s, char *t) { int i,j,k; /* counters */ int opt[3]; /* cost of the three options */ for (i=0; i