Last active
August 20, 2018 08:34
-
-
Save lala7573/e1fad8892fd02e404c58 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package codejam | |
import java.io.{File, PrintStream} | |
import scala.annotation.tailrec | |
import scala.io.Source | |
case class Food(expiration: Int, satiety : Int) { | |
val sum = expiration + satiety | |
} | |
object Survivor { | |
def findMaxDate(foods : List[Food]) : Int = { | |
val greedyFoods = foods.sortBy(-_.sum) | |
def canReach(remain:List[Food], date : Int) : Boolean = { | |
if(remain.isEmpty || date < 0 || remain.head.sum < date) return false // remain.head.sum means 'can reach'. it always bigger or equal than date. | |
date == 0 || // find solution | |
canReach(remain.tail, date - remain.head.satiety) || // eat remain.head | |
canReach(remain.tail, date) // not eat remain.head | |
} | |
@tailrec | |
def inner(date : Int) : Int = | |
if(canReach(greedyFoods, date)) date else inner(date-1) | |
inner(greedyFoods.head.sum) | |
} | |
def process(iter: Iterator[String])(pr: String => Unit) { | |
for (count <- 1 to iter.next().toInt) yield { | |
val foods = (for(n <- 1 to iter.next().toInt) yield { | |
val Array(p, s) = iter.next().split(" ").map(_.toInt) | |
Food(p, s) | |
}).toList | |
pr(s"Case #$count: ${findMaxDate(foods)}") | |
} | |
} | |
def main(args: Array[String]) { | |
val in = Source.fromFile(new File("A-large-practice.in.txt")) | |
val out = new PrintStream(new File("A-large-practice.out")) | |
try { | |
val start = System.currentTimeMillis() | |
process(in.getLines) { s: String => out.println(s) } | |
println(System.currentTimeMillis() - start) | |
} finally { | |
out.flush; out.close | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment