-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path497.go
74 lines (66 loc) · 1.28 KB
/
497.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
// UVa 497 - Strategic Defense Initiative
package main
import (
"fmt"
"io"
"os"
"sort"
)
type node struct{ num, idx int }
func find(s [][]node) int {
// for home-made binary search, see UVa 481
return sort.Search(len(s), func(i int) bool {
nodes := s[i]
return nodes[len(nodes)-1].num >= 2
})
}
func lis(h []int) [][]node {
s := [][]node{{{h[0], 0}}}
for i := 1; i < len(h); i++ {
if last := s[len(s)-1]; h[i] > last[len(last)-1].num {
t := []node{{h[i], i}}
s = append(s, t)
} else {
idx := find(s)
nd := s[idx]
tn := node{h[i], i}
nd = append(nd, tn)
s[idx] = nd
}
}
return s
}
func output(out io.Writer, s [][]node, l int) {
var f []int
k := len(s)
fmt.Fprintf(out, "Max hits: %d\n", k)
for i := k - 1; i >= 0; i-- {
nodes := s[i]
for j := len(nodes) - 1; j >= 0; j-- {
if nodes[j].idx < l {
f = append(f, nodes[j].num)
break
}
}
}
for i := len(f) - 1; i >= 0; i-- {
fmt.Fprintln(out, f[i])
}
}
func main() {
in, _ := os.Open("497.in")
defer in.Close()
out, _ := os.Create("497.out")
defer out.Close()
var n, tmp int
for fmt.Fscanf(in, "%d\n\n", &n); n > 0; n-- {
var h []int
for {
if _, err := fmt.Fscanf(in, "%d", &tmp); err != nil {
break
}
h = append(h, tmp)
}
output(out, lis(h), len(h))
}
}