CSES Solutions
#1639Dynamic Programming

Edit Distance

View on CSES

Solution

1639-Edit_Distance.cpp
1#include<bits/stdc++.h>
2using namespace std;
3#define int long long
4signed main(){
5  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
6  string s, t;
7  cin >> s >> t;
8  int n = s.size(), m = t.size();
9  int dp[n+1][m+1];
10  for(int i=0;i<=n;++i) dp[i][0]=i;
11  for(int j=0;j<=m;++j) dp[0][j]=j;
12  for(int i=1; i<=n; ++i) for(int j=1; j<=m; ++j) {
13    if(s[i-1]==t[j-1])
14      dp[i][j] = dp[i-1][j-1];
15    else
16      dp[i][j] = min({dp[i-1][j], dp[i][j-1],dp[i-1][j-1]}) + 1;
17  }
18  cout << dp[n][m] << '\n';
19  return 0;
20}

Editorial not yet generated for this problem. Run the editorial generation script to add hints and detailed explanations.