Skip to content

Instantly share code, notes, and snippets.

@theodoreLee
Created May 15, 2015 13:21
Show Gist options
  • Save theodoreLee/b21caf14a9a351c55d8b to your computer and use it in GitHub Desktop.
Save theodoreLee/b21caf14a9a351c55d8b to your computer and use it in GitHub Desktop.
import java.io.FileOutputStream
import scala.io.Source
object MushroomMonster {
val INPUT = "A-large-practice.in"
val OUTPUT = INPUT.takeWhile(_ != '.') + ".out"
def main(args: Array[String]): Unit = {
val itr = Source.fromFile(INPUT).getLines()
val sets = itr.next().toInt
val writer = new FileOutputStream(OUTPUT)
// val writer = Console.out
try {
Console.withOut(writer) {
for (set <- 1 to sets) {
itr.next()
val mushrooms = itr.next().split(' ').map(_.toInt)
println(s"Case #$set: ${solve1(mushrooms)} ${solve2(mushrooms)}")
}
}
} finally {
writer.flush()
writer.close()
}
}
/**
* 아무때나 막 먹는 경우의 최소 수
*/
def solve1(mushrooms: Array[Int]): Int = {
def _solve(m: IndexedSeq[Int], head: Int, accr: Int = 0): Int = m match {
case _ if m.isEmpty => accr
case x +: xs if head <= x => _solve(xs, x, accr)
case x +: xs => _solve(xs, x, accr + head - x)
}
_solve(mushrooms.tail, mushrooms.head)
}
/**
* 정해진 속도로 먹을 때 최소의 수.
* @param mushrooms
* @return
*/
def solve2(mushrooms: Array[Int]): Int = {
val m = mushrooms.tail.foldLeft((0, mushrooms.head)){
case ((maxValue, head), x) => (maxValue max (head - x), x)
}._1
def _solve(mush: IndexedSeq[Int], accr: Int = 0): Int = mush match {
case _ if mush.length == 1 => accr
case x +: xs if m <= x => _solve(xs, accr + m)
case x +: xs => _solve(xs, accr + x)
}
_solve(mushrooms)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment