02.2 go fast, O(N*M)

This commit is contained in:
Fedor Lyanguzov
2024-12-02 22:06:35 +03:00
parent 6ebdfde50c
commit 1b030a3821
+73 -28
View File
@@ -5,7 +5,6 @@ import (
"os" "os"
"strconv" "strconv"
"strings" "strings"
"slices"
) )
func SplitByLines(bytes []byte) []string { func SplitByLines(bytes []byte) []string {
@@ -27,32 +26,86 @@ func Abs(x int) int {
} }
return x return x
} }
func Safe1(l []int, j, e int) bool { func Safe1(l []int) bool {
if l[0] == l[1] {
return false
}
f := Less f := Less
if l[j-1]>l[j] { f = More } if l[0] > l[1] {
for j<e && P(f, l[j-1], l[j]){ f = More
}
j := 1
for j < len(l) && P(f, l[j-1], l[j]) {
j++ j++
} }
r := j<e r := j < len(l)
return !r return !r
} }
func Safe2(l []int) bool { func Safe2(l []int) bool {
if l[0]==l[1] { return false } cl := 0
f := Less cm := 0
if l[0]>l[1] { f = More } cq := 0
c := 0 il := -1
j := 2 im := -1
for j<len(l) && c<2 { iq := -1
if !(P(f, l[j-1], l[j])) && (P(f, l[j-2], l[j])) { for i := 1; i < len(l); i++ {
c++ a := l[i-1]
b := l[i]
if a >= b {
cl++
if il == -1 {
il = i
} }
j++
} }
return c<2 if a <= b {
cm++
if im == -1 {
im = i
}
}
if Abs(a-b) > 3 {
cq++
if iq == -1 {
iq = i
}
}
}
if cq == 0 && (cm == 0 || cl == 0) {
return true
}
if cq > 2 || cl > 2 && cm > 2 {
return false
}
if cq == 2 {
return Safe1(Skip(l, iq))
}
if iq != -1 {
return Safe1(Skip(l, iq)) || Safe1(Skip(l, iq-1))
}
if 0 < cl && cl <= 2 {
return Safe1(Skip(l, il)) || Safe1(Skip(l, il-1))
}
if 0 < cm && cm <= 2 {
return Safe1(Skip(l, im)) || Safe1(Skip(l, im-1))
}
return false
}
func Skip(l []int, i int) []int {
n := make([]int, len(l)-1)
k := 0
for j, x := range l {
if j != i {
n[k] = x
k++
}
}
return n
} }
func main() { func main() {
bytes, err := os.ReadFile("./input.txt") bytes, err := os.ReadFile("./input.txt")
if err != nil { panic(err) } if err != nil {
panic(err)
}
lines := SplitByLines(bytes) lines := SplitByLines(bytes)
data := make([][]int, len(lines)) data := make([][]int, len(lines))
for i, l := range lines { for i, l := range lines {
@@ -66,24 +119,16 @@ func main() {
} }
s := 0 s := 0
for _, l := range data { for _, l := range data {
if Safe1(l, 1, len(l)) { s++ } if Safe1(l) {
s++
}
} }
fmt.Println(s) fmt.Println(s)
s = 0 s = 0
for _, l := range data { for _, l := range data {
t := make([]int, len(l)) if Safe2(l) {
copy(t, l)
t = slices.Delete(t, 1, 2)
if Safe1(l, 1, len(l)) ||
Safe1(l, 2, len(l)) ||
Safe1(t, 1, len(t)) ||
Safe1(l, 1, len(l)-1) {
s++
} else if Safe2(l) {
fmt.Println(l)
s++ s++
} }
} }
fmt.Println(s) fmt.Println(s)
println(len(data))
} }