-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathtask.go
121 lines (96 loc) · 1.81 KB
/
task.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
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
type GoldenHeap struct {
price int
num int
}
func main() {
s := strings.Builder{}
Solution(os.Stdin, &s)
fmt.Println(s.String())
}
func Solution(r io.Reader, s *strings.Builder) {
var totalCost int
m, k, data := getData(bufio.NewScanner(r))
data = merge(data)
for i := 0; i < k && m > 0; i++ {
for g := 0; g < data[i].num && m > 0; g++ {
totalCost += data[i].price
m--
}
}
s.WriteString(fmt.Sprint(totalCost))
}
func getData(scanner *bufio.Scanner) (m, k int, items []GoldenHeap) {
var err error
scanner.Scan()
m, err = strconv.Atoi(scanner.Text())
if err != nil {
log.Fatal(err)
}
scanner.Scan()
k, err = strconv.Atoi(scanner.Text())
if err != nil {
log.Fatal(err)
}
items = make([]GoldenHeap, k)
var a, b int
for i := 0; i < k; i++ {
scanner.Scan()
arrStr := strings.Split(scanner.Text(), " ")
a, err = strconv.Atoi(arrStr[0])
if err != nil {
log.Fatal(err)
}
b, err = strconv.Atoi(arrStr[1])
if err != nil {
log.Fatal(err)
}
items[i] = GoldenHeap{
price: a,
num: b,
}
}
return
}
func merge(mine []GoldenHeap) []GoldenHeap {
mineLength := len(mine)
if mineLength < 2 {
return mine
}
mid := mineLength >> 1
a := merge(mine[:mid])
aLength := len(a)
b := merge(mine[mid:])
bLength := len(b)
var aIndex, bIndex int
result := make([]GoldenHeap, 0, mineLength)
for aIndex < aLength || bIndex < bLength {
if aIndex == aLength {
result = append(result, b[bIndex])
bIndex++
continue
}
if bIndex == bLength {
result = append(result, a[aIndex])
aIndex++
continue
}
if a[aIndex].price >= b[bIndex].price {
result = append(result, a[aIndex])
aIndex++
} else {
result = append(result, b[bIndex])
bIndex++
}
}
return result
}