fork(3) download
  1. object Main {
  2. case class Company(members: Int, cost: Int)
  3. def main(args: Array[String]) {
  4. val safetyToInt = (x:String) => x.filter("0123456789" contains _).toInt
  5. val needs, cNum = safetyToInt(readLine())
  6. val companies = Iterator.continually(readLine()).take(cNum).
  7. map{_.split(' ').map(safetyToInt)}.
  8. map{x => Company(members = x(0), cost = x(1))}.toList
  9.  
  10. def search[T1, T2](f: (Either[T2, T2], T1)=> Either[T2, T2],
  11. xs: Seq[T1], prev: Either[T2, T2]):Either[T2, T2] =
  12. if (xs.headOption.isEmpty) prev
  13. else f(prev, xs.head) match {
  14. case l @ Left(_) => search(f, xs.tail, l)
  15. case r @ Right(_) if xs.tail.nonEmpty =>
  16. search(f, xs.head +: xs.tail.tail, Left(r.right.get))
  17. case e @ _ => prev
  18. }
  19. case class Cpr(best: Int, mem: Int, cst: Int)
  20. def compair
  21. (min: Int)(prev: Either[Cpr, Cpr], crnt: Company): Either[Cpr, Cpr] = {
  22. val Cpr(best, mem, cst) = prev.left.get
  23. val next = mem + crnt.members
  24. val newCost = cst + crnt.cost;
  25. println(prev);
  26. (if(next >= min) Right(Cpr(best.min(newCost), mem, cst))
  27. else Left(Cpr(best, next, newCost)))
  28. }
  29.  
  30. val most = companies.map{_.cost}.sum;
  31. val result =
  32. companies.tails.foldLeft(Left(Cpr(most, 0, 0)):Either[Cpr, Cpr]){
  33. (x, y) => search(compair(needs) _, y, Left(Cpr(x.left.get.best, 0, 0)))
  34. };
  35. println("result: " + result)
  36. }
  37. }
  38.  
Success #stdin #stdout 0.39s 382144KB
stdin
250 
5 
35 3640 
33 2706 
98 9810 
57 5472 
95 7790
stdout
Left(Cpr(29418,0,0))
Left(Cpr(29418,35,3640))
Left(Cpr(29418,68,6346))
Left(Cpr(29418,166,16156))
Left(Cpr(29418,223,21628))
Left(Cpr(29418,0,0))
Left(Cpr(29418,33,2706))
Left(Cpr(29418,131,12516))
Left(Cpr(29418,188,17988))
Left(Cpr(29418,0,0))
Left(Cpr(29418,98,9810))
Left(Cpr(29418,155,15282))
Left(Cpr(29418,0,0))
Left(Cpr(29418,57,5472))
Left(Cpr(29418,0,0))
result: Left(Cpr(29418,0,0))