Skip to content

Instantly share code, notes, and snippets.

@okaq
Created May 12, 2015 17:18
Show Gist options
  • Save okaq/d3c0892a46fdb1bbc5fd to your computer and use it in GitHub Desktop.
Save okaq/d3c0892a46fdb1bbc5fd to your computer and use it in GitHub Desktop.
Google Code Jam 2015 * Round 1A * Problem A. Mushroom Monster
/*
* Google Code Jam
* 2015 Round 1A
* Problem A. Mushroom Monster
* AQ <[email protected]>
*/
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
)
const (
IN = "A-large-practice.in"
OUT = "A-large-practice.out"
)
var (
I *os.File
O *os.File
S *bufio.Scanner
W *bufio.Writer
T int
Sh []*Shroom
WG sync.WaitGroup
)
type Shroom struct {
N int
M []int
Y int
Z int
}
func NewShroom() *Shroom {
return &Shroom{}
}
func (sh *Shroom) Solve() {
sh.Y = sh.First()
sh.Z = sh.Second()
WG.Done()
}
func (sh *Shroom) First() int {
min := 0
for i := 1; i < sh.N; i++ {
min += Max(0, sh.M[i-1]-sh.M[i])
}
return min
}
func (sh *Shroom) Second() int {
max := 0
for i := 1; i < sh.N; i++ {
max = Max(max, sh.M[i-1]-sh.M[i])
}
min := 0
for i := 0; i < sh.N-1; i++ {
min += Min(sh.M[i], max)
}
return min
}
func Max(a, b int) int {
if a > b {
return a
}
return b
}
func Min(a, b int) int {
if a < b {
return a
}
return b
}
func Load() {
var err error
I, err = os.Open(IN)
if err != nil {
fmt.Println(err)
}
S = bufio.NewScanner(I)
O, err = os.Create(OUT)
if err != nil {
fmt.Println(err)
}
W = bufio.NewWriter(O)
}
func Cases() {
var err error
S.Scan()
T, err = strconv.Atoi(S.Text())
if err != nil {
fmt.Println(err)
}
fmt.Printf("%d test cases. \n", T)
}
func Split() {
var err error
Sh = make([]*Shroom, T)
for i := 0; i < T; i++ {
sh := NewShroom()
S.Scan()
sh.N, err = strconv.Atoi(S.Text())
S.Scan()
a := strings.Split(S.Text(), " ")
sh.M = make([]int, len(a))
for j := 0; j < len(a); j++ {
sh.M[j], err = strconv.Atoi(a[j])
}
if err != nil {
fmt.Println(err)
}
Sh[i] = sh
// fmt.Println(sh)
WG.Add(1)
go Sh[i].Solve()
}
}
func Finish() {
defer I.Close()
defer O.Close()
for i := 0; i < T; i++ {
s0 := fmt.Sprintf("Case #%d: %d %d\n", i+1, Sh[i].Y, Sh[i].Z)
W.WriteString(s0)
}
W.Flush()
}
func main() {
begin := time.Now()
fmt.Println("mushroom monster ok!")
Load()
Cases()
Split()
WG.Wait()
Finish()
end := time.Now()
fmt.Printf("total run time: %v.\n", end.Sub(begin))
}
// fast linear accumulation solutions
// total run time: 111ms large input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment