-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path10261.go
77 lines (70 loc) · 1.33 KB
/
10261.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
// UVa 10261 - Ferry Loading
package main
import (
"fmt"
"io"
"os"
)
var (
out io.WriteCloser
pre [][]int
)
func output(index, length int) {
if index == 0 {
return
}
output(index-1, pre[index][length])
if pre[index][length] == length {
fmt.Fprintln(out, "port")
} else {
fmt.Fprintln(out, "starboard")
}
}
func solve(ferry int, cars []int) {
num := len(cars)
dp := make([][]bool, num)
pre = make([][]int, num)
for i := range dp {
dp[i] = make([]bool, ferry+1)
pre[i] = make([]int, ferry+1)
}
dp[0][0] = true
var sum, last, length int
for i := 1; i <= num; i++ {
sum += cars[i-1]
for j := 0; j <= ferry; j++ {
switch {
case sum-j <= ferry && dp[i-1][j]:
pre[i][j] = j
dp[i][j], last, length = true, i, j
case j >= cars[i-1] && dp[i-1][j-cars[i-1]]:
pre[i][j] = j - cars[i-1]
dp[i][j], last, length = true, i, j
}
}
}
fmt.Fprintln(out, last)
output(last, length)
}
func main() {
in, _ := os.Open("10261.in")
defer in.Close()
out, _ = os.Create("10261.out")
defer out.Close()
var kase int
var ferry, car int
for fmt.Fscanf(in, "%d", &kase); kase > 0; kase-- {
fmt.Fscanf(in, "\n%d", &ferry)
var cars []int
for {
if fmt.Fscanf(in, "%d", &car); car == 0 {
break
}
cars = append(cars, car)
}
solve(ferry*100, cars)
if kase > 1 {
fmt.Fprintln(out)
}
}
}