loulett

HW3_Levenstein

Dec 15th, 2014
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <cstring>
  4.  
  5. int min(int a, int b, int c)
  6. {
  7.     if (a < b && a < c)
  8.         return a;
  9.     else if (b < c)
  10.         return b;
  11.     else
  12.         return c;
  13. }
  14.  
  15. int main()
  16. {
  17.     int n = 0, m = 0;
  18.     scanf("%d", &n);
  19.     scanf("%d", &m);
  20.     char* str1 = (char*)malloc((n + 1)*sizeof(char));
  21.     scanf("%s", str1);
  22.     str1[n] = '0';
  23.     char* str2 = (char*)malloc((m + 1)*sizeof(char));
  24.     scanf("%s", str2);
  25.     str2[m] = '0';
  26.     int** matrix = (int**)malloc((m + 1)*sizeof(int*));
  27.     for (int i = 0; i <= m; ++i)
  28.     {
  29.         matrix[i] = (int*)malloc((n + 1)*sizeof(int));
  30.         if (!i)
  31.         {
  32.             for (int j = 0; j <= n; ++j)
  33.             {
  34.                 matrix[i][j] = j;
  35.                 printf("%d ", matrix[i][j]);
  36.             }
  37.         }
  38.         else
  39.         {
  40.             printf("\n");
  41.             matrix[i][0] = i;
  42.             printf("%d ", matrix[i][0]);
  43.             for (int j = 1; j <= n; ++j)
  44.             {
  45.                 if (str1[j-1] == str2[i-1])
  46.                     matrix[i][j] = min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1, matrix[i - 1][j - 1]);
  47.                 else
  48.                     matrix[i][j] = min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1, matrix[i - 1][j - 1] + 1);
  49.                 printf("%d ", matrix[i][j]);
  50.             }
  51.         }
  52.     }
  53.     printf("\n");
  54.     printf("%d\n", matrix[m][n]);
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment