-
Notifications
You must be signed in to change notification settings - Fork 22
/
edist.java
94 lines (77 loc) · 2.45 KB
/
edist.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.io.*;
import java.util.*;
import static java.lang.Integer.parseInt;
public class edist
{
private static BufferedReader f;
public static final int MATCH = 1;
public static final int INSERT = 2;
public static final int DELETE = 3;
public static final int REPLACE = 4;
public static void main(String[] args) throws IOException {
f = new BufferedReader(new InputStreamReader(System.in));
int T = parseInt(f.readLine());
while(T-- > 0)
{
System.out.println(match(f.readLine(), f.readLine()));
System.out.flush();
}
System.exit(0);
}
private static int match(String x, String y)
{
if(x == null || x.length() == 0 || y == null || y.length() == 0) return 0;
char[] a = x.toCharArray();
char[] b = y.toCharArray();
int n = a.length;
int m = b.length;
int[][] dp = new int[n+1][m+1];
int[][] parent = new int[n+1][m+1];
int i, j;
dp[0][0] = 0; parent[0][0] = 0;
for(i = 1; i <= n; i++) {
parent[i][0] = INSERT;
dp[i][0] = dp[i-1][0] + insert(a[i-1]);
}
for(i = 1; i <= m; i++) {
parent[0][i] = DELETE;
dp[0][i] = dp[0][i-1] + delete(b[i-1]);
}
for(i = 1; i <= n; i++) {
for(j = 1; j <= m; j++) {
if(a[i-1] == b[j-1]) {
dp[i][j] = dp[i-1][j-1] + match();
parent[i][j] = MATCH;
} else {
dp[i][j] = dp[i-1][j-1] + replace(a[i-1],b[j-1]);
parent[i][j] = REPLACE;
}
if(dp[i-1][j] + insert(a[i-1]) < dp[i][j]) {
dp[i][j] = dp[i-1][j] + insert(a[i-1]);
parent[i][j] = INSERT;
}
if(dp[i][j-1] + delete(b[j-1]) < dp[i][j]) {
dp[i][j] = dp[i][j-1] + delete(b[j-1]);
parent[i][j] = DELETE;
}
}
}
return dp[n][m];
}
private static int replace(char a, char b)
{
return 1;
}
private static int delete(char a)
{
return 1;
}
private static int insert(char b)
{
return 1;
}
private static int match()
{
return 0;
}
}