Блог пользователя Raythroughspace

Автор Raythroughspace, история, 5 лет назад, По-английски
#include <bits/stdc++.h>
using namespace std;

int main() {
  string a, b;
  cin >> a >> b;
  int na = a.size(), nb = b.size();
  vector<vector<int>> dp(na+1, vector<int>(nb+1,1e9));
  dp[0][0] = 0;
  for (int i = 0; i <= na; i++) {
    for (int j = 0; j <= nb; j++) {
      if (i) {
	dp[i][j] = min(dp[i][j], dp[i-1][j]+1);
      }
      if (j) {
	dp[i][j] = min(dp[i][j], dp[i][j-1]+1);
      }
      if (i && j) {
	dp[i][j] = min(dp[i][j], dp[i-1][j-1]+(a[i-1] != b[j-1]));
      }
    }
  }
  cout << dp[na][nb] << endl;
}

In the recursion, they consider the cases where you remove the last letter of the first or second strings and when you match the last letters of both strings. I can intuitively feel this is correct but how can you justify this rigorously? (ie these cases will give the same distance as in the more general case where you can replace/remove/insert any letter, not just from the rightmost side?)

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится