import scala.annotation.tailrec import scala.io.StdIn object Problem253 { val threshold: Int = 50 def question(len: Int): Int = { println("? " + len) StdIn.readInt() } def answer(len: Int): Unit = { println("! " + len) } def waitBurnout(): Int = (1 to threshold + 1).find(x => question(0) == 0).get def search(): Int = { @tailrec def searchR(min: Int, max: Int, burned: Int): Int = { val mid = (min + max) / 2 question(mid) match { case 1 => searchR(mid - 1, max - 1, burned + 1) case 0 => mid + burned case -1 => searchR(min - 1, mid - 1, burned + 1) } } val min = threshold val max = Math.pow(10, 9).toInt searchR(min, max, 1) } def proc(): Int = { question(threshold) match { case 1 => search() // 二分探索 case 0 => threshold // 一回で当たった case -1 => waitBurnout() // 0以下の処理が面倒なので長さが閾値以下の場合は燃え尽きるまで待つ } } def main(args: Array[String]): Unit = { val result = proc() answer(result) } }