abc185_e - Sequence Matching
18 Dec 2020 — Tags: dp — URLLol, it was edit distance. Editorial
Time complexity: $O(n^2)$
Memory complexity: $O(n^2)$
Click to show code.
using namespace std;
using ll = long long;
using ii = pair<int, int>;
using vi = vector<int>;
int solve(vi a, vi b)
{
int const INF = 1e8;
int n = (int)(a).size(), m = (int)(b).size();
vector<vi> dp(n + 1, vi(m + 1, INF));
for (int i = 0; i <= n; ++i)
dp[i][0] = i;
for (int j = 0; j <= m; ++j)
dp[0][j] = j;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= m; ++j)
{
auto &ans = dp[i][j];
ans = min(ans, dp[i - 1][j] + 1);
ans = min(ans, dp[i][j - 1] + 1);
ans = min(ans, dp[i - 1][j - 1] + (a[i - 1] != b[j - 1]));
}
}
return dp[n][m];
}
int main(void)
{
ios::sync_with_stdio(false), cin.tie(NULL);
int n, m;
cin >> n >> m;
vi a(n), b(m);
read_n(begin(a), n);
read_n(begin(b), m);
cout << solve(a, b) << endl;
return 0;
}