-
Notifications
You must be signed in to change notification settings - Fork 27
/
526.go
148 lines (136 loc) · 2.23 KB
/
526.go
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// UVa 526 - String Distance and Transform Process
package main
import (
"fmt"
"io"
"os"
)
func make2d(d1, d2 int) [][]int {
s := make([][]int, d1)
for i := range s {
s[i] = make([]int, d2)
}
return s
}
func trace(op [][]int) []string {
var e []string
l1, l2 := len(op)-1, len(op[0])-1
for l1 != 0 && l2 != 0 {
switch cur := op[l1][l2]; cur {
case 0:
l1--
l2--
e = append(e, "M")
case 1:
l1--
l2--
e = append(e, "C")
case 2:
l2--
e = append(e, "I")
case 3:
l1--
e = append(e, "D")
}
}
for l1 != 0 {
e = append(e, "D")
l1--
}
for l2 != 0 {
e = append(e, "I")
l2--
}
return e
}
func edit(s1, s2 string) [][]int {
l1, l2 := len(s1), len(s2)
dp := make2d(l1+1, l2+1)
op := make2d(l1+1, l2+1)
for i := range dp {
dp[i][0] = i
}
for i := range dp[0] {
dp[0][i] = i
}
var k int
for i := 1; i <= l1; i++ {
for j := 1; j <= l2; j++ {
if s1[i-1] == s2[j-1] {
k = 0
} else {
k = 1
}
switch dp[i][j] = min(dp[i-1][j-1]+k, min(dp[i-1][j]+1, dp[i][j-1]+1)); dp[i][j] {
case dp[i-1][j-1] + k:
if k == 0 {
op[i][j] = 0 // move
} else {
op[i][j] = 1 // change
}
case dp[i][j-1] + 1:
op[i][j] = 2 // insert
default:
op[i][j] = 3 // delete
}
}
}
return op
}
func nonMove(e []string) int {
count := 0
for _, v := range e {
if v != "M" {
count++
}
}
return count
}
func output(out io.Writer, e []string, s2 string) {
fmt.Fprintln(out, nonMove(e))
count := 0
p, p1, p2 := 1, 0, 0
for i := len(e) - 1; i >= 0; i-- {
switch e[i] {
case "M":
p++
p1++
p2++
case "C":
count++
fmt.Fprintf(out, "%d Replace %d,%c\n", count, p, s2[p2])
p++
p1++
p2++
case "I":
count++
fmt.Fprintf(out, "%d Insert %d,%c\n", count, p, s2[p2])
p++
p2++
case "D":
count++
fmt.Fprintf(out, "%d Delete %d\n", count, p)
p1++
}
}
}
func main() {
in, _ := os.Open("526.in")
defer in.Close()
out, _ := os.Create("526.out")
defer out.Close()
var s1, s2 string
for first := true; ; {
if _, err := fmt.Fscanf(in, "%s", &s1); err != nil {
break
}
if first {
first = false
} else {
fmt.Fprintln(out)
}
fmt.Fscanf(in, "%s", &s2)
e := trace(edit(s1, s2))
output(out, e, s2)
}
}