-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_583.cpp
More file actions
55 lines (48 loc) · 1.21 KB
/
Copy pathP_583.cpp
File metadata and controls
55 lines (48 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <bits/stdc++.h>
#define fast_io \
ios::sync_with_stdio(false); \
cin.tie(nullptr);
using namespace std;
int dp[505][505];
int dfs(string& w1, string& w2, int i, int j) {
if (i == w1.length() || j == w2.length()) {
return 0;
}
if (dp[i][j] != -1) {
return dp[i][j];
}
int res = max(dfs(w1, w2, i + 1, j), dfs(w1, w2, i, j + 1));
if (w1[i] == w2[j]) {
res = max(res, 1 + dfs(w1, w2, i + 1, j + 1));
}
return dp[i][j] = res;
}
int minDistanceDFS(string word1, string word2) {
for (int i = 0; i <= word1.length(); i++) {
for (int j = 0; j <= word2.length(); j++) {
dp[i][j] = -1;
}
}
return word1.length() + word2.length() - 2 * dfs(word1, word2, 0, 0);
}
int minDistance(string word1, string word2) {
int n = word1.length();
int m = word2.length();
int dp[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
dp[i][j] = 0;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (word1[i] == word2[j]) {
dp[i + 1][j + 1] = dp[i][j] + 1;
} else {
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]);
}
}
}
int lcs = dp[n][m];
return n + m - 2 * lcs;
}