import scala.annotation.tailrec
object Main extends App {

  import scala.io.StdIn._

  solve
  def solve: Unit = {
    val expression = readLine
    if (expression == null) return
    Expression.calculate(expression) match {
      case Some(c) ⇒ println(c)
      case None ⇒ println("overflow")
    }
    solve
  }

  case class Real(value: Int) {
    def +(that: Real): Real = Real(value + that.value)
    def -(that: Real): Real = Real(value - that.value)
    def *(that: Real): Real = Real(value * that.value)
    def *(that: Image): Image = Image(value * that.value)
    override def toString: String = if (value == 0) "" else s"$value"
  }
  case class Image(value: Int) {
    def +(that: Image): Image = Image(value + that.value)
    def -(that: Image): Image = Image(value - that.value)
    def *(that: Image): Real = Real(-value * that.value)
    def *(that: Real): Image = Image(value * that.value)
    override def toString: String = if (value == 0) "" else if (value > 0) s"${value}i" else s"${value}i"
  }
  case class ComplexType(real: Real = Real(0), image: Image = Image(0)) {
    def +(that: ComplexType): ComplexType = ComplexType(real + that.real, image + that.image)
    def -(that: ComplexType): ComplexType = ComplexType(real - that.real, image - that.image)
    def *(that: ComplexType): ComplexType = ComplexType(real * that.real + image * that.image, real * that.image + image * that.real)
    def isOverflow: Boolean = math.abs(real.value) > 10000 || math.abs(image.value) > 10000
    def overflowChecked: Option[ComplexType] = if (isOverflow) None else Some(this)
    override def toString(): String = {
      if (real.value == 0 && image.value != 0){
        image.toString
      }else if (real.value == 0){
        "0"
      }else if (image.value == 0){
        real.toString
      }else if (image.value > 0){
        s"$real+$image"
      }else {
        s"$real$image"
      }
    }
  }
  object Expression{
    def calculate(expression: String): Option[ComplexType] = {
      expression.toList match {
        case f Expression Nil ⇒ f
        case _ ⇒ ???
      }
    }
    def unapply(arg: List[Char]): Option[(Option[ComplexType], List[Char])] = {
      arg match {
        case left Term rest ⇒ Some(parseAll(rest, left))
        case _ ⇒ None
      }
    }
    @tailrec
    private def parseAll(arg: List[Char], left: Option[ComplexType]): (Option[ComplexType], List[Char]) = {
      arg match {
        case '+'::(right Term t) ⇒ parseAll(t, left.flatMap(l ⇒ right.map(r ⇒ l + r)).filterNot(_.isOverflow))
        case '-'::(right Term t) ⇒ parseAll(t, left.flatMap(l ⇒ right.map(r ⇒ l - r)).filterNot(_.isOverflow))
        case _ ⇒ (left, arg)
      }
    }
  }

  object Term {
    def unapply(arg: List[Char]): Option[(Option[ComplexType], List[Char])] = {
      arg match {
        case f Factor rest ⇒ Some(parseAll(rest, f))
        case _ ⇒ None
      }
    }
    @tailrec
    private def parseAll(arg: List[Char], left: Option[ComplexType]): (Option[ComplexType], List[Char]) = {
      arg match {
        case '*'::(right Factor t) ⇒ parseAll(t, left.flatMap(l ⇒ right.map(r ⇒ l * r)).filterNot(_.isOverflow))
        case _ ⇒ (left, arg)
      }
    }
  }
  object Factor {
    def unapply(arg: List[Char]): Option[(Option[ComplexType], List[Char])] = {
      arg match {
        case '('::(f Expression ')'::t) ⇒ Some(f, t)
        case r Number t ⇒ Some(r.flatMap(real ⇒ ComplexType(real = real).overflowChecked), t)
        case i Image t ⇒ Some(ComplexType(image = i).overflowChecked, t)
      }
    }
  }
  object Image{
    def unapply(arg: List[Char]): Option[(Image, List[Char])] = {
      arg match {
        case 'i'::t ⇒ Some(Image(1), t)
        case _ ⇒ None
      }
    }
  }
  object Number{
    def unapply(arg: List[Char]): Option[(Option[Real], List[Char])] = {
      arg.span(_.isDigit) match {
        case (Nil, _) ⇒ None
        case (number, t) ⇒ Some(number.foldLeft(Some(0):Option[Int]){(o, r) ⇒ o.map(l ⇒ l * 10 + r.asDigit).filterNot(i ⇒ math.abs(i) > 10000)}.map(i ⇒ Real(i)), t)
      }
    }
  }
  implicit class Extension[T](val value :T) extends AnyVal {
    @inline
    def let[A](@inline func: T ⇒ A): A = func(value)
    @inline
    def also(@inline func: T ⇒ Unit): T = {func(value); value}
  }
}

Calculation of Expressions

Write a program to calculate values of arithmetic expressions which may
involve complex numbers. Details of the expressions are described below.

In this problem, basic elements of expressions are
non-negative integer numbers and
the special symbol "i". Integer numbers are sequences
of digits of arbitrary length and are in decimal notation. "i" denotes the
unit imaginary number i, i.e. i 2 = -1.

Operators appearing in expressions are + (addition), -
(subtraction), and * (multiplication). Division is excluded from
the repertoire of the operators. All three operators are only used as binary
operators. Unary plus and minus operators (e.g., -100) are also
excluded from the repertoire. Note that the multiplication symbol *
may not be omitted in any case. For example, the expression 1+3i
in mathematics should be written as 1+3*i.

Usual formation rules of arithmetic expressions apply. Namely, (1) The
operator * binds its operands stronger than the operators +
and -. (2) The operators + and - have the same
strength in operand binding. (3) Two operators of the same strength bind
from left to right. (4) Parentheses are used to designate specific order
of binding.

The consequence of these rules can easily be understood from the following
examples.

(1) 3+4*5 is 3+(4*5), not (3+4)*5

(2) 5-6+7 is (5-6)+7, not 5-(6+7)

(3) 1+2+3 is (1+2)+3, not 1+(2+3)

Your program should successively read expressions, calculate them and
print their results. Overflow should be detected.

Whenever an abnormal value is yielded as a result of applying an operator
appearing in the given expression,
your program should report that the calculation failed due to overflow.
By "an abnormal value", we mean a value
whose real part or imaginary part is
greater than 10000 or less than -10000. Here are examples:

10000+1+(0-10)

overflow, not 9991

(10*i+100)*(101+20*i)

9900+3010i , not overflow

4000000-4000000

overflow, not 0

Note that the law of associativity does not necessarily hold in this
problem. For example, in the first example,
overflow is detected by interpreting
the expression as (10000+1)+(0-10) following the binding rules,
whereas overflow could not be detected
if you interpreted it as 10000+(1+(0-10)).
Moreover, overflow detection should take place for resulting value of each
operation.

In the second example, a value which exceeds 10000 appears
in the calculation process of one multiplication
if you use the mathematical rule

(a+b i)(c+d i)=(ac-bd)+(ad+bc)i
.

But the yielded result 9900+3010i does not contain any number
which exceeds 10000 and, therefore, overflow should not be reported.

Input

A sequence of lines each of which contains an expression is given as
input. Each line consists of less than 100 characters and does not contain
any blank spaces. You may assume that all expressions given in the sequence
are syntactically correct.

Output

Your program should produce output for each expression line by line.
If overflow is detected, output should be
a character string "overflow".
Otherwise, output should be the resulting value of calculation
in the following fashion.

0 , if the result is 0+0i.

-123 , if the result is -123+0i.

45i , if the result is 0+45i.

3+1i , if the result is 3+i.

123-45i , if the result is 123-45i.

Output should not contain any blanks, surplus 0,
+, or -.

Sample Input

(1-10*i)+00007+(3+10*i)
3+4*i*(4+10*i)
(102+10*i)*(99+10*i)
2*i+3+9999*i+4

Output for the Sample Input

11
-37+16i
9998+2010i
overflow


object Main{
  def cut(cards: Array[Int],p:Int,c:Int): Array[Int] = {
    cards.slice(p-1,p-1+c) ++ cards.take(p-1) ++ cards.drop(p+c-1)
  }
  def main(args: Array[String]){
    var nr = readLine.split(" ").map( n => n.toInt )
    var n = nr(0)
    var r = nr(1)
    while(n>0&&r>0){
      var cards = new Array[Int](n)
      for(i <- 0 until n) cards(i) = n-i
      for(i <- 0 until r){
        val pc = readLine.split(" ").map( n => n.toInt )
        val p = pc(0)
        val c = pc(1)
        cards = cut(cards,p,c)
      }
      println( cards.head )
      nr = readLine.split(" ").map( n => n.toInt )
      n = nr(0)
      r = nr(1)
    }
  }
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Problem A: Hanafuda Shuffle

There are a number of ways to shuffle a deck of cards. Hanafuda
shuffling for Japanese card game 'Hanafuda' is one such example.
The following is how to perform Hanafuda shuffling.

There is a deck of n cards. Starting from the p-th card
from the top of the deck, c cards are pulled out
and put on the top of the deck, as shown in Figure 1.
This operation, called a cutting operation, is repeated.

Write a program that simulates Hanafuda shuffling and answers which
card will be finally placed on the top of the deck.

Figure 1: Cutting operation

Input

The input consists of multiple data sets.
Each data set starts with a line containing two positive integers n
(1 <= n <= 50) and r (1 <= r <= 50); n and
r are the number of cards in the deck and the number of cutting
operations, respectively.

There are r more lines in the data set, each of which
represents a cutting operation. These cutting operations
are performed in the listed order.
Each line contains two positive integers p and c
(p + c <= n + 1).
Starting from the p-th card from the top of the deck, c
cards should be pulled out and put on the top.

The end of the input is indicated by a line which contains two zeros.

Each input line contains exactly two integers separated by a space
character.
There are no other characters in the line.

Output

For each data set in the input, your program
should write the number of the top card after the shuffle.
Assume that at the beginning the cards
are numbered from 1 to n, from the bottom to the top.
Each number should be written in a separate line
without any superfluous characters such as leading or following spaces.

Sample Input

5 2
3 1
3 1
10 3
1 10
10 1
8 3
0 0

Output for the Sample Input

4
4

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


object Main extends App {
    val in = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
    for (Array(n, r) <- in if n > 0 && r > 0) {
        val m = in.take(r).foldRight(0)((r, i) =>
            if (i >= r(0) - 1 + r(1)) i
            else if (i >= r(1)) i - r(1)
            else i + r(0) - 1
        )
        println(n - m)
    }
}


import scala.collection.mutable._
import io.StdIn.readInt
import io.StdIn.readLine

object Main extends App {
  val out = new java.io.PrintWriter(System.out)

  def calculate(q:Array[Int],d:Array[Array[Int]]):Int = {
    val ts = q(0)
    val te = q(1)
    val st = q(2)

    val a = d.filter(_(2) == st)
    val map = new HashMap[Int,Array[Int]]
    val log = ListBuffer.empty[Tuple2[Int,Int]]
    a.foreach(l => {
      if(l(3) == 1) map.put(l(1),l)
      else {
        val e = map.remove(l(1)).get
        log += {( e(0), l(0) )}
        }
    })
    // println(log.mkString)

    val time = Array.ofDim[Int](721)
    log.par.foreach(t => {
      val s = math.max(ts, t._1) -540
      val e = math.min(te, t._2) -540
      (s until e).foreach(time(_) = 1)
    })
    time.sum
  }

  def solve(s:String):Unit = {
    val Array(n, m) = s.split(" ").map(_.toInt)
    val r = readInt
    val d = Iterator.continually(readLine)
      .take(r)
      .map(_.split(" ").map(_.toInt))
      .toArray
    val q = readInt
    Iterator.continually(readLine)
      .take(q)
      .map(_.split(" ").map(_.toInt))
      .foreach(qd => out.println(calculate(qd,d)))
  }

  Iterator.continually(readLine)
    .takeWhile(_ != "0 0")
    .foreach(solve(_))

  out.flush
}

Problem B: Analyzing Login/Logout Records

You have a computer literacy course in your university. In the computer
system, the login/logout records of all PCs in a day are stored in a
file. Although students may use two or more PCs at a time, no one can
log in to a PC which has been logged in by someone who has not
logged out of that PC yet.

You are asked to write a program that calculates the total time of a
student that he/she used at least one PC in a given time period
(probably in a laboratory class) based on the records in the file.

The following are example login/logout records.

The student 1 logged in to the PC 1 at 12:55

The student 2 logged in to the PC 4 at 13:00

The student 1 logged in to the PC 2 at 13:10

The student 1 logged out of the PC 2 at 13:20

The student 1 logged in to the PC 3 at 13:30

The student 1 logged out of the PC 1 at 13:40

The student 1 logged out of the PC 3 at 13:45

The student 1 logged in to the PC 1 at 14:20

The student 2 logged out of the PC 4 at 14:30

The student 1 logged out of the PC 1 at 14:40

For a query such as "Give usage of the student 1 between 13:00 and
14:30", your program should answer "55 minutes", that is, the sum of
45 minutes from 13:00 to 13:45 and 10 minutes from 14:20 to 14:30, as
depicted in the following figure.

Input

The input is a sequence of a number of datasets.
The end of the input is indicated by a line containing two zeros
separated by a space.
The number of datasets never exceeds 10.

Each dataset is formatted as follows.

N M

r

record1

...

recordr

q

query1

...

queryq

The numbers N  and M  in the first line are the numbers of
PCs and the students, respectively. r  is the number of
records. q  is the number of queries. These four are integers
satisfying the following.

1 ≤ N  ≤ 1000, 1 ≤ M  ≤ 10000, 2 ≤ r  ≤ 1000, 1 ≤ q  ≤ 50

Each record consists of four integers, delimited by a space, as follows.

t  n  m  s

s  is 0 or 1.
If s  is 1, this line means that the student m  logged in
to the PC n  at time t . If s  is 0, it means that
the student m  logged out of the PC n  at time t .
The time is expressed as elapsed minutes from 0:00 of the day.
t , n  and m  satisfy the following.

540 ≤ t  ≤ 1260,
1 ≤ n  ≤ N , 1 ≤ m  ≤ M

You may assume the following about the records.

Records are stored in ascending order of time t.

No two records for the same PC has the same time t.

No PCs are being logged in before the time of the first record
nor after that of the last record in the file.

Login and logout records for one PC appear alternatingly, and each of the login-logout record pairs is for the same student.

Each query consists of three integers delimited by a space, as follows.

ts  te  m

It represents "Usage of the student m  between
ts  and te ".
ts , te  and m
satisfy the following.

540 ≤ ts  < te  ≤ 1260,
1 ≤ m  ≤ M

Output

For each query, print a line having a decimal integer indicating the
time of usage in minutes. Output lines should not have any character
other than this number.

Sample Input

4 2
10
775 1 1 1
780 4 2 1
790 2 1 1
800 2 1 0
810 3 1 1
820 1 1 0
825 3 1 0
860 1 1 1
870 4 2 0
880 1 1 0
1
780 870 1
13 15
12
540 12 13 1
600 12 13 0
650 13 15 1
660 12 15 1
665 11 13 1
670 13 15 0
675 11 13 0
680 12 15 0
1000 11 14 1
1060 12 14 1
1060 11 14 0
1080 12 14 0
3
540 700 13
600 1000 15
1000 1200 11
1 1
2
600 1 1 1
700 1 1 0
5
540 600 1
550 650 1
610 620 1
650 750 1
700 800 1
0 0

Output for the Sample Input

55
70
30
0
0
50
10
50
0


import java.util.Scanner

import scala.collection.Searching._
import scala.annotation.tailrec
import scala.collection.immutable.Queue

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(new Node(None, 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  @tailrec
  private def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) => root(p)
  }
}

object Main {
  def solve(sc: => Scanner): Unit = {
    var M, C, N = sc.nextInt
    var i = 0
    var f = true
    while (M != 0 && C != 0 && N != 0) {
      val A = Array.fill(N)(Array.fill(sc.nextInt)(sc.nextInt))
      var B = List.fill(0)(0)
      for (j <- 0 until 100) {
        for (i <- 0 until N) {
          if (j < A(i).size) {
            B = B :+ A(i)(j)
          }
        }
      }

      System.gc()

      val que = Array.fill[Queue[Int]](M)(Queue[Int]())
      var ans = 0
      for (x <- B) {
        var findpoint = M
        i = 0
        f = true
        while (i < M && f) {
          val findindex = que(i).indexOf(x)
          if (findindex != -1) {
            que(i) = que(i).take(findindex - 1) ++ que(i).drop(findindex + 1)
            //println(findindex)
            //println(que(i).take(findindex - 1))
            // println(que(i).drop(findindex + 1))
            findpoint = i
            f = false
          }
          i += 1
        }
        ans += findpoint + 1
        var returnpoint = M
        i = 0
        while (i < M) {
          if (que(i).size < C) {
            returnpoint = math.min(returnpoint, i)
          }
          i += 1
        }
        ans += returnpoint + 1
        //println("--", ans)
        if (returnpoint == 0) {
          que(0) ++= List(x)
        } else {
          var returnpoint2 = M
          i = 0
          f = true
          while (i < M && f) {
            if (que(i).size + (if (returnpoint == i) (1) else (0)) + 1 <= C) {
              returnpoint2 = math.min(returnpoint2, i)
              f = false
            }
            i += 1
          }
          if (returnpoint != 0) {
            ans += 1 + returnpoint2 + 1
            //println("--",ans)
            val first = que(0).head
            que(0) = que(0).drop(1)
            if (returnpoint2 != M) {
              que(returnpoint2) ++= List(first)
            }
          }
          que(0) ++= List(x)
          ans += 1 + returnpoint + 1
          //println("--",ans,returnpoint)
        }
        //println(que.mkString(" "))
        //println(ans)
      }
      println(ans)
      M = sc.nextInt
      C = sc.nextInt
      N = sc.nextInt
      System.gc()
    }
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)

    solve(sc)
  }

}

Problem B: Book Replacement

The deadline of Prof. Hachioji’s assignment is tomorrow. To complete the task, students have
to copy pages of many reference books in the library.

All the reference books are in a storeroom and only the librarian is allowed to enter it. To obtain
a copy of a reference book’s page, a student should ask the librarian to make it. The librarian
brings books out of the storeroom and makes page copies according to the requests. The overall
situation is shown in Figure 1.

Students queue up in front of the counter. Only a single book can be requested at a time. If a
student has more requests, the student goes to the end of the queue after the request has been
served.

In the storeroom, there are m desks D1, ... , Dm, and a shelf. They are placed in a line in this
order, from the door to the back of the room. Up to c books can be put on each of the desks. If
a student requests a book, the librarian enters the storeroom and looks for it on D1, ... , Dm in
this order, and then on the shelf. After finding the book, the librarian takes it and gives a copy
of a page to the student.

Then the librarian returns to the storeroom with the requested book, to put it on D1 according to the following procedure.

If D1 is not full (in other words, the number of books on D1 < c), the librarian puts the requested book there.

If D1 is full, the librarian

temporarily puts the requested book on the non-full desk closest to the entrance or,
in case all the desks are full, on the shelf,

finds the book on D1 that has not been requested for the longest time (i.e. the least recently used book) and takes it,

puts it on the non-full desk (except D1 ) closest to the entrance or, in case all the desks except D1 are full, on the shelf,

takes the requested book from the temporary place,

and finally puts it on D1 .

Your task is to write a program which simulates the behaviors of the students and the librarian,
and evaluates the total cost of the overall process. Costs are associated with accessing a desk
or the shelf, that is, putting/taking a book on/from it in the description above. The cost of an
access is i for desk Di and m + 1 for the shelf. That is, an access to D1, ... , Dm , and the shelf
costs 1, ... , m, and m + 1, respectively. Costs of other actions are ignored.

Initially, no books are put on desks. No new students appear after opening the library.

Input

The input consists of multiple datasets. The end of the input is indicated by a line containing
three zeros separated by a space. It is not a dataset.

The format of each dataset is as follows.

m c n
k1
b11 . . . b1k1
.
.
.
kn
bn1 . . . bnkn

Here, all data items are positive integers. m is the number of desks not exceeding 10. c is the number of books allowed to put on a desk, which does not exceed 30. n is the number of
students not exceeding 100. ki is the number of books requested by the i-th student, which does
not exceed 50. bij is the ID number of the book requested by the i-th student on the j-th turn.
No two books have the same ID number. Note that a student may request the same book more
than once. bij is less than 100.

Here we show you an example of cost calculation for the following dataset.

3 1 2
3
60 61 62
2
70 60

In this dataset, there are 3 desks (D1, D2, D3 ). At most 1 book can be put on each desk. The
number of students is 2. The first student requests 3 books of which IDs are 60, 61, and 62,
respectively, and the second student 2 books of which IDs are 70 and 60, respectively.

The calculation of the cost for this dataset is done as follows. First, for the first request of the
first student, the librarian takes the book 60 from the shelf and puts it on D1 and the first
student goes to the end of the queue, costing 5. Next, for the first request of the second student,
the librarian takes the book 70 from the shelf, puts it on D2, moves the book 60 from D1 to D3 ,
and finally moves the book 70 from D2 to D1 , costing 13. Similarly, the cost for the books 61,
60, and 62, are calculated as 14, 12, 14, respectively. Therefore, the total cost is 58.

Output

For each dataset, output the total cost of processing all the requests, in a separate line.

Sample Input

2 1 1
1
50
2 1 2
1
50
1
60
2 1 2
2
60 61
1
70
4 2 3
3
60 61 62
1
70
2
80 81
3 1 2
3
60 61 62
2
70 60
1 2 5
2
87 95
3
96 71 35
2
68 2
3
3 18 93
2
57 2
2 2 1
5
1 2 1 3 1
0 0 0

Output for the Sample Input

4
16
28
68
58
98
23


import scala.annotation.tailrec

object Main extends App {

  override def main(args: Array[String]): Unit = {
    val answerMap = Solver.solveAll
    import scala.io.{StdIn => in}
    Iterator.continually(in.readLine()).takeWhile(str => !(str startsWith "0 0 0")).map(_.split(" ")).map(arr => new Solver(arr(0).toInt, arr(1).toInt, arr(2).toInt))
      .map(solver => solver.solve(answerMap)).foreach(println)
  }

}

sealed trait Coordination {
  val x: Int
  val y: Int
}

object Coordination {
  def apply(x: Int, y: Int): Coordination =
    if (((x + y) & 1) == 1) OddCoordination(x, y)
    else EvenCoordination(x, y)

}

case class OddCoordination(x: Int, y: Int) extends Coordination {}

case class EvenCoordination(x: Int, y: Int) extends Coordination {}

case class Face(bottom: Int, southOrNorth: Int)

sealed trait CoordinationAndFace {
  val coordination: Coordination
  val face: Face

  def next: Seq[CoordinationAndFace]

  val toKeySring: String = List(coordination.x, coordination.y, face.bottom, face.southOrNorth).mkString(",")
}

object CoordinationAndFace {
  def apply(coordination: Coordination, face: Face): CoordinationAndFace = {
    coordination match {
      case e: EvenCoordination => EvenCoordinationAndFace(e, face)
      case o: OddCoordination => OddCoordinationAndFace(o, face)
    }
  }
}

case class EvenCoordinationAndFace(coordination: EvenCoordination, face: Face) extends CoordinationAndFace {
  override def next = Seq(toNorth, toSouthEast, toSouthWest)

  val now = IcosahedronFaces(face.bottom)(face.southOrNorth)

  def toNorth: CoordinationAndFace = {
    val newCoordination = Coordination(coordination.x, coordination.y + 1)
    val nextFace = IcosahedronFaces(now.top)(now.n)
    val newFace = Face(nextFace.n, nextFace.top)
    CoordinationAndFace(newCoordination, newFace)
  }

  def toSouthWest: CoordinationAndFace = {
    val newCoordination = Coordination(coordination.x - 1, coordination.y)
    val nextFace = IcosahedronFaces(now.right)(now.n)
    val newFace = Face(nextFace.n, nextFace.left)
    CoordinationAndFace(newCoordination, newFace)
  }

  def toSouthEast: CoordinationAndFace = {
    val newCoordination = Coordination(coordination.x + 1, coordination.y)
    val nextFace = IcosahedronFaces(now.left)(now.n)
    val newFace = Face(nextFace.n, nextFace.right)
    CoordinationAndFace(newCoordination, newFace)
  }
}

case class OddCoordinationAndFace(coordination: OddCoordination, face: Face) extends CoordinationAndFace {
  override def next = Seq(toSouth, toNorthEast, toNorthWest)

  val now = IcosahedronFaces(face.bottom)(face.southOrNorth)

  def toSouth: CoordinationAndFace = {
    val newCoordination = Coordination(coordination.x, coordination.y - 1)
    val nextFace = IcosahedronFaces(now.top)(now.n)
    val newFace = Face(nextFace.n, nextFace.top)
    CoordinationAndFace(newCoordination, newFace)
  }

  def toNorthWest: CoordinationAndFace = {
    val newCoordination = Coordination(coordination.x - 1, coordination.y)
    val nextFace = IcosahedronFaces(now.left)(now.n)
    val newFace = Face(nextFace.n, nextFace.right)
    CoordinationAndFace(newCoordination, newFace)
  }

  def toNorthEast: CoordinationAndFace = {
    val newCoordination = Coordination(coordination.x + 1, coordination.y)
    val nextFace = IcosahedronFaces(now.right)(now.n)
    val newFace = Face(nextFace.n, nextFace.left)
    CoordinationAndFace(newCoordination, newFace)
  }

}

sealed case class IcosahedronFace(n: Int, top: Int, left: Int, right: Int) {
  def apply(asTop: Int): IcosahedronFace = {
    asTop match {
      case `top` => this
      case `left` => IcosahedronFace(n, left, right, top)
      case `right` => IcosahedronFace(n, right, top, left)
    }
  }
}

object IcosahedronFaces {
  private val list = List(
    IcosahedronFace(0, 5, 1, 4),
    IcosahedronFace(1, 6, 2, 0),
    IcosahedronFace(2, 7, 3, 1),
    IcosahedronFace(3, 8, 4, 2),
    IcosahedronFace(4, 9, 0, 3),
    IcosahedronFace(5, 0, 10, 11),
    IcosahedronFace(6, 1, 11, 12),
    IcosahedronFace(7, 2, 12, 13),
    IcosahedronFace(8, 3, 13, 14),
    IcosahedronFace(9, 4, 14, 10),
    IcosahedronFace(10, 15, 5, 9),
    IcosahedronFace(11, 16, 6, 5),
    IcosahedronFace(12, 17, 7, 6),
    IcosahedronFace(13, 18, 8, 7),
    IcosahedronFace(14, 19, 9, 8),
    IcosahedronFace(15, 10, 19, 16),
    IcosahedronFace(16, 11, 15, 17),
    IcosahedronFace(17, 12, 16, 18),
    IcosahedronFace(18, 13, 17, 19),
    IcosahedronFace(19, 14, 18, 15)
  )

  def apply(n: Int): IcosahedronFace = n match {
    case n: Int if ((0 to 19).contains(n)) => list(n)
  }
}

class Solver(x: Int, y: Int, n: Int) {

  import Solver._

  def solve(answerMap: Array[Int]): Int = {
    if (-100 > x || -100 > y || x >= 100 || y >= 100) {
      val coordination = Coordination(x, y)
      val missing = coordination match {
        case e: EvenCoordination => 100
        case o: OddCoordination => 99
      }
      return missing
    }

    val coordination = Coordination(x, y)
    val missing = coordination match {
      case e: EvenCoordination => 100
      case o: OddCoordination => 99
    }

    val iface = IcosahedronFaces(n)

    val keys = List(
      CoordinationAndFace(coordination, Face(n, iface.top)),
      CoordinationAndFace(coordination, Face(n, iface.left)),
      CoordinationAndFace(coordination, Face(n, iface.right))
    )

    keys.map(cf => answerMap(coordinationAndFaceToInt(cf))).map(v => if (v == 0) missing else v).min
  }

}

object Solver {

  def solveAll: Array[Int] = {
    val init: CoordinationAndFace = CoordinationAndFace(Coordination(0, 0), Face(0, 5))

    import scala.collection.mutable.{Queue => MQueue}

    def solveInner(map: Array[Int], queue: MQueue[(Int, Int)]): Boolean = {
      val head = queue.dequeue()
      if (head._2 < 98) {
        val candidate = intToCoordinationAndFace(head._1).next
        val nextCost = head._2 + 1
        candidate.filter(cf => map(coordinationAndFaceToInt(cf)) == 0).foreach {
          next =>
            map(coordinationAndFaceToInt(next)) = nextCost
            queue.enqueue((coordinationAndFaceToInt( next), nextCost))
        }
        true
      }
      else false
    }

    val map = Array.ofDim[Int](xWidth * xPosition)
    val queue = MQueue(coordinationAndFaceToInt(init) -> 0)
    while(solveInner(map, queue)){}
    map
  }

  val xOffset = 100
  val yOffset = 100
  val xWidth = 200
  val yWidth = 200
  val bottomWidth = 20
  val southOrNorthWidth = 20

  val southOrNorthPosition = 1
  val bottom = southOrNorthWidth * southOrNorthPosition
  val yPosition = bottomWidth * bottom
  val xPosition = yWidth * yPosition

  def toInt(x: Int, y: Int, buttom: Int, southOrNorth: Int): Int = {
    (x + xOffset) * xPosition + (y + yOffset) * yPosition + (buttom) * bottom + (southOrNorth) * southOrNorthPosition
  }

  def fromInt(int: Int): (Int, Int, Int, Int) = {
    ((int / xPosition) - xOffset, (int / yPosition) % yWidth - yOffset, (int / bottom) % bottomWidth, (int / southOrNorthPosition) % southOrNorthWidth)
  }

  def coordinationAndFaceToInt(coordinationAndFace: CoordinationAndFace): Int = {
    val x = coordinationAndFace.coordination.x
    val y = coordinationAndFace.coordination.y
    val bottom = coordinationAndFace.face.bottom
    val southOrNorth = coordinationAndFace.face.southOrNorth
    toInt(x, y, bottom, southOrNorth)
  }

  def intToCoordinationAndFace(int: Int): CoordinationAndFace = {
    val (x, y, bottom, southOrNorth) = fromInt(int)
    CoordinationAndFace(Coordination(x, y), Face(bottom, southOrNorth))
  }

}

Problem E: Driving an Icosahedral Rover

After decades of fruitless efforts, one of the expedition teams of ITO (Intersolar Tourism Organization) finally found a planet that would surely provide one of the best tourist attractions
within a ten light-year radius from our solar system. The most attractive feature of the planet,
besides its comfortable gravity and calm weather, is the area called Mare Triangularis. Despite
the name, the area is not covered with water but is a great plane. Its unique feature is that it is
divided into equilateral triangular sections of the same size, called trigons. The trigons provide
a unique impressive landscape, a must for tourism. It is no wonder the board of ITO decided
to invest a vast amount on the planet.

Despite the expected secrecy of the staff, the Society of Astrogeology caught this information
in no time, as always. They immediately sent their president's letter to the Institute of Science
and Education of the Commonwealth Galactica claiming that authoritative academic inspections
were to be completed before any commercial exploitation might damage the nature.

Fortunately, astrogeologists do not plan to practice all the possible inspections on all of the
trigons; there are far too many of them. Inspections are planned only on some characteristic
trigons and, for each of them, in one of twenty different scientific aspects.

To accelerate building this new tourist resort, ITO's construction machinery team has already succeeded in putting their brand-new
invention in practical use. It is a rover vehicle of the shape of an icosahedron, a regular polyhedron with twenty faces of equilateral triangles.
The machine is customized
so that each of the twenty faces exactly fits each of the trigons.
Controlling the high-tech gyromotor installed inside its body, the rover can roll onto one of the three trigons neighboring the one its bottom is
on.

Figure E.1: The Rover on Mare Triangularis

Each of the twenty faces has its own function. The set of equipments installed on the bottom
face touching the ground can be applied to the trigon it is on. Of course, the rover was meant to accelerate construction of the luxury hotels to host rich interstellar travelers, but, changing
the installed equipment sets, it can also be used to accelerate academic inspections.

You are the driver of this rover and are asked to move the vehicle onto the trigon specified by
the leader of the scientific commission with the smallest possible steps. What makes your task
more difficult is that the designated face installed with the appropriate set of equipments has to
be the bottom. The direction of the rover does not matter.

Figure E.2:The Coordinate System

Figure E.3: Face Numbering

The trigons of Mare Triangularis are given two-dimensional coordinates as shown in Figure E.2.
Like maps used for the Earth, the x axis is from the west to the east, and the y axis is from the
south to the north. Note that all the trigons with its coordinates (x , y) has neighboring trigons
with coordinates (x - 1 , y) and (x + 1 , y). In addition to these, when x + y is even, it has a
neighbor (x , y + 1); otherwise, that is, when x + y is odd, it has a neighbor (x , y - 1).

Figure E.3 shows a development of the skin of the rover. The top face of the development
makes the exterior. That is, if the numbers on faces of the development were actually marked
on the faces of the rover, they should been readable from its outside. These numbers are used
to identify the faces.

When you start the rover, it is on the trigon (0,0) and the face 0 is touching the ground. The
rover is placed so that rolling towards north onto the trigon (0,1) makes the face numbered 5
to be at the bottom.

As your first step, you can choose one of the three adjacent trigons, namely those with coordinates (-1,0), (1,0),
and (0,1), to visit. The bottom will be the face numbered 4, 1, and 5,
respectively. If you choose to go to (1,0) in the first rolling step, the second step can bring
the rover to either of (0,0), (2,0), or (1,-1). The bottom face will be either of 0, 6, or 2,
correspondingly. The rover may visit any of the trigons twice or more, including the start and the goal trigons, when appropriate.

The theoretical design section of ITO showed that the rover can reach any goal trigon on the
specified bottom face within a finite number of steps.

Input

The input consists of a number of datasets. The number of datasets does not exceed 50.

Each of the datasets has three integers x, y, and n in one line, separated by a space. Here, (x,y)
specifies the coordinates of the trigon to which you have to move the rover, and n specifies the
face that should be at the bottom.

The end of the input is indicated by a line containing three zeros.

Output

The output for each dataset should be a line containing a single integer that gives the minimum
number of steps required to set the rover on the specified trigon with the specified face touching
the ground. No other characters should appear in the output.

You can assume that the maximum number of required steps does not exceed 100. Mare Triangularis
is broad enough so that any of its edges cannot be reached within that number of
steps.

Sample Input

0 0 1
3 5 2
-4 1 3
13 -13 2
-32 15 9
-50 50 0
0 0 0

Output for the Sample Input

6
10
9
30
47
100


object Main extends App {

  import scala.io.StdIn._
  import scala.math._
  val n = readLine.trim.toInt
  val planets = Array.tabulate(n){_ ⇒
    val Array(x, y) = readLine.trim.split(' ').map(_.toInt.toRational)
    Coordinate(x, y)
  }
  println(
    planets.tail.permutations.map{p ⇒ minLine(p.toList, planets.head)}.min
  )
  def minLine(planets: List[Coordinate], start: Coordinate): Int = {
    def sub(planets: List[Coordinate], current: Coordinate, lines: List[Line]): Int = {
      planets match {
        case Nil ⇒ lines.length
        case h::t ⇒
          val line = verticalHalf(current, h)
          if (lines.contains(line)) sub(t, h, lines)
          else sub(t, h, line::lines)
      }
    }
    sub(planets, start, Nil)
  }

  def verticalHalf(a: Coordinate, b: Coordinate): Line = {
    val mid = a + b match {case Coordinate(x, y) ⇒ Coordinate(x / 2.toRational, y / 2.toRational)}
    val diff = a - b  match {case Coordinate(x, y) ⇒ Coordinate(-y, x)}
    new Line(mid, mid + diff)
  }
  class Line(private val from: Coordinate, private val to: Coordinate){
    override def toString: String = s"Line($from, $to)"
    private def dx: Rational = (to - from).x
    private def dy: Rational = (to - from).y
    def isOnLine(point: Coordinate): Boolean = {
      point - from match {
        case Coordinate(x, y) ⇒
          val ddx = dx
          val ddy = dy
          ddx * y == ddy * x
      }
    }
    override def equals(obj: Any): Boolean = {
      obj match {
        case line: Line ⇒ isOnLine(line.from) && isOnLine(line.to)
        case _ ⇒ super.equals(obj)
      }
    }
  }
  object Rational{
    def apply(numerator: Long, denominator: Long): Rational = {
      val g = gcd(math.abs(numerator), math.abs(denominator))
      val signum = numerator.signum * denominator.signum
      new Rational(signum * math.abs(numerator / g), math.abs(denominator / g))
    }
    private def gcd(a: Long, b: Long): Long = {
      b match {
        case 0l ⇒ a
        case _ ⇒ gcd(b, a % b)
      }
    }
  }
  implicit class ToRational(val value: Int){
    def toRational: Rational = Rational(value, 1)
  }
  class Rational private (private val numerator: Long, private val denominator: Long) extends Ordered[Rational] {
    def +(that: Rational): Rational = Rational(numerator * that.denominator + denominator * that.numerator, denominator * that.denominator)
    def -(that: Rational): Rational = Rational(numerator * that.denominator - denominator * that.numerator, denominator * that.denominator)
    def *(that: Rational): Rational = Rational(numerator * that.numerator, denominator * that.denominator)
    def /(that: Rational): Rational = Rational(numerator * that.denominator, denominator * that.numerator)
    def unary_-(): Rational = Rational(-numerator, denominator)
    override def compare(that: Rational): Int = (this - that).numerator.compare(0)

    override def equals(obj: Any): Boolean = {
      obj match {
        case r: Rational ⇒ this.compare(r) == 0
        case _ ⇒ super.equals(obj)
      }
    }
    override def toString: String = s"$numerator / $denominator"
  }
  case class Coordinate(x: Rational, y: Rational){
    def -(that: Coordinate): Coordinate = Coordinate(x - that.x, y - that.y)
    def +(that: Coordinate): Coordinate = Coordinate(x + that.x, y + that.y)
  }
  implicit class Extension[T](val value :T){
    def also(func: T ⇒ Unit): T = {
      func(value)
      value
    }
    def let[R](func: T ⇒ R): R = func(value)
  }
}

Reflection Warp Machine

Problem

とある宇宙では、2次元の格子点上にn個の星が存在し、宇宙人達はReflection Warp Machineを使い、星間を移動している。

この装置は、任意の位置、角度で直線を引くことができる。

この直線を対称軸として、現在いる座標から線対称の座標に移動することができる。

ただし、星が存在しない座標に移動することはできない。

一度引いた直線は何度でも利用できる。

現在、(x0,y0)の星にいるある宇宙人はすべての星を訪れたいと考えている。

星は好きな順番に訪れることができる。

すべての星を訪れるのに最小で何本の直線を引く必要があるか求めよ。

Input

n
x0 y0
...
xn−1 yn−1

入力は全て整数で与えられる。

1行目にnが与えられる。

2行目以降n行にi番目の星の座標(xi,yi)が空白区切りで与えられる。

Constraints

2 ≤ n ≤ 8

−100 ≤ xi,yi ≤ 100

(xi,yi) ≠ (xj,yj) (i ≠ j)

Output

すべての星を訪れるために必要な最小の直線の数を1行に出力せよ。

Sample Input 1

3
0 0
0 1
1 0

Sample Output 1

2

Sample Input 2

4
0 0
0 1
0 2
0 3

Sample Output 2

2


import java.util.Scanner

object Main {

  val scan = new Scanner(System.in)

  def main(args: Array[String]): Unit = {
    val W = scan.nextInt()
    val H = scan.nextInt()
    val T = scan.nextInt()
    val p = scan.nextInt()
    val g = Array.ofDim[Int](H, W)
    for (i <- 0 until p) {
      val x = scan.nextInt()
      val y = scan.nextInt()
      val t = scan.nextInt()
      g(y)(x) += 1
    }
    var sum = 0
    for (i <- 0 until H; j <- 0 until W) {
      val s = scan.nextInt()
      sum += s * g(i)(j)
    }
    println(s"${sum}")
  }

}

Problem A: Plants

Problem

がっちょ君は横W個×縦H個のマスで区切られた畑を所有している。x列目y行目のマスをマス (x, y) と呼ぶことにする。いくつかのマスの土地には高さ0cmの植物が1本だけ植えてあり、その他のマスの土地には何も植えられていない。

がっちょ君はある時刻に畑に肥料をまく。肥料がまかれたマスに植物が植えられているとき、その植物の高さが1cm伸びる。植物が植えられていないときは、何もおこらない。植物が伸びるのにかかる時間はとても短いので無視できる。がっちょ君は同じ時刻に複数のマスに肥料をまくことができる。ただし、同じ時刻に同じマスに2度以上肥料をまくことはない。

がっちょ君が肥料をまいた記録が与えられたとき、時刻T時点での畑の植物の高さの和を計算せよ。

Input

入力は以下の形式で与えられる。

W H T
p
x0 y0 t0
x1 y1 t1
...
xp−1 yp−1 tp−1
s0,0 s1,0 … sW−1,0
s0,1 s1,1 … sW−1,1
...
s0,H−1 s1,H−1 … sW−1,H−1

1行目に畑の横幅W、畑の縦幅H、時刻Tが与えられる。がっちょ君は時刻Tまでに肥料をまきおえる。

2行目にがっちょ君が肥料をまいた回数pが与えられる。

3行目から2+p行目までに与えられる３つの整数は、がっちょ君が時刻tiにマス(xi, yi)に肥料をまいたことを表す。

3+p行目から2+p+H行目までは、最初の畑のそれぞれのマスに植物が植えられているかどうかを表すW×H個の整数が与えられる。sj,kが1のときマス(j, k)に高さ0cmの植物が1本だけ植えられていることを表し、sj,kが0のときマス(j, k)に植物は1本も植えられていないことを表す。

Constraints

1 ≤ W, H, T ≤ 50

0 ≤ p ≤ min(W×H×T, 50)

0 ≤ xi < W

0 ≤ yi < H

0 ≤ ti < T

sj,k = 0または1

Output

時刻Tでの畑の植物の高さの和を1行に出力せよ。

Sample Input 1

3 3 3
5
2 0 0
0 1 0
1 1 1
1 2 1
2 2 0
0 0 0
0 1 0
0 0 0

Sample Output 1

1

Sample Input 2

2 3 4
2
0 0 0
1 1 3
1 0
0 0
0 0

Sample Output 2

1

Sample Input 3

3 8 6
6
0 4 3
2 5 3
0 2 3
2 2 5
1 1 3
2 2 1
1 1 1
1 1 1
1 1 1
1 0 1
0 1 1
1 1 0
1 0 1
0 1 0

Sample Output 3

4

Sample Input 4

8 3 3
7
0 1 1
5 1 0
4 0 2
3 2 0
3 1 1
3 0 1
5 1 1
1 0 1 1 0 0 1 0
0 0 1 1 0 1 0 1
0 1 0 0 0 1 0 1

Sample Output 4

4


import scala.util.control.Breaks

object Main extends App{
  def main(N:Int,s:List[Int]) {
    var res=1000000000
    for(i<-0 until N-1) {
      res=List(res,s(i+1)-s(i)).min
    }
    println(res)
  }
  val sc = new java.util.Scanner(System.in)
  val b=new Breaks

  b.breakable {
    while (true) {
      val N = sc.nextInt
      if (N == 0) b.break
      val s = List.fill(N)(sc.nextInt)
      main(N, s.sorted)
    }
  }
}

Selection of Participants of an Experiment

Dr. Tsukuba has devised a new method of programming training.
In order to evaluate the effectiveness of this method,
he plans to carry out a control experiment.
Having two students as the participants of the experiment,
one of them will be trained under the conventional method
and the other under his new method.
Comparing the final scores of these two,
he will be able to judge the effectiveness of his method.

It is important to select two students having the closest possible scores,
for making the comparison fair.
He has a list of the scores of all students
who can participate in the experiment.
You are asked to write a program which selects two of them
having the smallest difference in their scores.

Input

The input consists of multiple datasets, each in the following format.

n

a1 a2 … an

A dataset consists of two lines.
The number of students n is given in the first line.
n is an integer satisfying 2 ≤ n ≤ 1000.
The second line gives scores of n students.
ai (1 ≤ i ≤ n) is the score of the i-th student, which is a non-negative integer not greater than 1,000,000.

The end of the input is indicated by a line containing a zero.
The sum of n's of all the datasets does not exceed 50,000.

Output

For each dataset, select two students with the smallest difference in their scores,
and output in a line (the absolute value of) the difference.

Sample Input

5
10 10 10 10 10
5
1 5 8 9 11
7
11 34 83 47 59 29 70
0

Output for the Sample Input

0
1
5


object Main extends App {
	// your code goes here
	import scala.io.StdIn.readLine
	while(true) {
		val n = readLine().toInt
		if (n == 0) System.exit(0)
		val list = readLine().split(" ").map(_.toInt)
		println(list.sorted.sliding(2).map{case Array(_1, _2) => _2 - _1}.min)
	}
}


import scala.io.StdIn
import java.util.Arrays

object Main {
  def main(args: Array[String]): Unit = {
    while(true) {
      val n :: m :: _res = StdIn.readLine().split(" ").map(_.toInt).toList
      if(n == 0) { return; }
      val prices = StdIn.readLine().split(" ").map(_.toInt).toSeq

      println(solve(m, prices).map(_.toString).getOrElse("NONE"))
    }
  }

  def solve(max: Int, prices: Seq[Int]): Option[Int] = {
    val ps = prices.toArray
    Arrays.sort(ps)

    var current: Int = 0

    for {
      (p, i) <- ps.zipWithIndex
      (q, j) <- ps.zipWithIndex
      if i < j
    } {
      val add = p + q
      if(add <= max) {
        if(current < add) {
          current = add
        }
      }
    }

    if(current == 0) {
      None
    } else {
      Some(current)
    }
  }
}

Taro's Shopping

Mammy decided to give Taro his first shopping experience.
Mammy tells him to choose any two items he wants from those
listed in the shopping catalogue,
but Taro cannot decide which two, as all the items look attractive.
Thus he plans to buy the pair of two items with
the highest price sum, not exceeding the amount Mammy allows.
As getting two of the same item is boring, he wants two different items.

You are asked to help Taro select the two items.
The price list for all of the items is given.
Among pairs of two items in the list,
find the pair with the highest price sum
not exceeding the allowed amount,
and report the sum.
Taro is buying two items, not one, nor three, nor more.
Note that, two or more items in the list may be priced equally.

Input

The input consists of multiple datasets, each in the following format.

n m
a1 a2 ... an

A dataset consists of two lines.
In the first line, the number of items n and the maximum
payment allowed m are given.
n is an integer satisfying 2 ≤ n ≤ 1000.
m is an integer satisfying 2 ≤ m ≤ 2,000,000.
In the second line, prices of n items are given.
ai (1 ≤ i ≤ n) is the price
of the i-th item.
This value is an integer greater than or equal to 1 and
less than or equal to 1,000,000.

The end of the input is indicated by a line containing two zeros.
The sum of n's of all the datasets does not exceed 50,000.

Output

For each dataset, find the pair with the highest price sum
not exceeding the allowed amount m
and output the sum in a line.
If the price sum of every pair of items exceeds m,
output NONE instead.

Sample Input

3 45
10 20 30
6 10
1 2 5 8 9 11
7 100
11 34 83 47 59 29 70
4 100
80 70 60 50
4 20
10 5 10 16
0 0

Output for the Sample Input

40
10
99
NONE
20


object Main extends App {
    val hands = List("Rock", "Fire", "Scissors", "Snake", "Human", "Tree", "Wolf", "Sponge", "Paper", "Air", "Water", "Dragon", "Devil", "Lightning", "Gun")
    val h = (hands ::: hands).sliding(8).take(15).map(l => (l.head, l.tail)).toMap
    val in = io.Source.stdin.getLines
    for (n <- in if n != "0") {
        val x = in.take(n.toInt).toList
        x.foldLeft(x)((a, b) => a.filterNot(h(b).contains _)) match {
            case _ if n == "1" => println("Draw")
            case x :: Nil => println(x)
            case _ => println("Draw")
        }
    }
}

Problem B: Hyper Rock-Scissors-Paper

Rock-Scissors-Paper is a game played with hands and often used for random choice of a person for some
purpose. Today, we have got an extended version, namely, Hyper Rock-Scissors-Paper (or Hyper RSP
for short).

In a game of Hyper RSP, the players simultaneously presents their hands forming any one of the following
15 gestures: Rock, Fire, Scissors, Snake, Human, Tree, Wolf, Sponge, Paper, Air, Water, Dragon, Devil,
Lightning, and Gun.

Figure 1: Hyper Rock-Scissors-Paper

The arrows in the figure above show the defeating relation. For example, Rock defeats Fire, Scissors,
Snake, Human, Tree, Wolf, and Sponge. Fire defeats Scissors, Snake, Human, Tree, Wolf, Sponge, and
Paper. Generally speaking, each hand defeats other seven hands located after in anti-clockwise order in
the figure. A player is said to win the game if the player’s hand defeats at least one of the other hands,
and is not defeated by any of the other hands.

Your task is to determine the winning hand, given multiple hands presented by the players.

Input

The input consists of a series of data sets. The first line of each data set is the number N of the players
(N < 1000). The next N lines are the hands presented by the players.

The end of the input is indicated by a line containing single zero.

Output

For each data set, output the winning hand in a single line. When there are no winners in the game,
output “Draw” (without quotes).

Sample Input

8
Lightning
Gun
Paper
Sponge
Water
Dragon
Devil
Air
3
Rock
Scissors
Paper
0

Output for the Sample Input

Sponge
Draw


import scala.io.StdIn

object Main {
  def printResult(R1: BigInt) {
    if(R1 < 0 || R1 >= 10000){
      println("E")
    }
    else{
      println(R1)
    }
  }
  def read(){
    StdIn.readLine() match {
      case line: String => {
        val digit = """(\d+)""".r
        var R1 = BigInt(0)
        var R2 = BigInt(0)
        var R3 = "+"
        val tokens = line.split("").toArray
        for(i <- 0 to tokens.length - 1){
          val x = tokens(i).toString
          x match {
            case digit(x) => {
              R2 = BigInt("10") * R2 + BigInt(x)
            }
            case "+" => {
              R1 = R1 + R2
              R2 = 0
              R3 = x
            }
            case "-" => {
              R1 = R1 - R2
              R2 = 0
              R3 = x
            }
            case "*" => {
              R1 = R1 * R2
              R2 = 0
              R3 = x
            }
            case "=" => {
              R3 match {
                case "+" => {
                  R1 = R1 + R2
                  R2 = 0
                  printResult(R1)
                }
                case "-" => {
                  R1 = R1 - R2
                  R2 = 0
                  printResult(R1)
                }
                case "*" => {
                  R1 = R1 * R2
                  R2 = 0
                  printResult(R1)
                }
                case _ => {
                  sys.exit()
                }
              }
            }
            case _ => {
              sys.exit()
            }
          }
        }
      }
      case _ => {
        return
      }
    }
    read()
  }
  def main(args: Array[String]){
    read()
  }
}

First Experience

After spending long long time, you had gotten tired of computer programming. Instead you were inter-
ested in electronic construction. As your first work, you built a simple calculator. It can handle positive
integers of up to four decimal digits, and perform addition, subtraction and multiplication of numbers.
You didn’t implement division just because it was so complicated. Although the calculator almost worked
well, you noticed that it displays unexpected results in several cases. So, you decided to try its simulation
by a computer program in order to figure out the cause of unexpected behaviors.

The specification of the calculator you built is as follows. There are three registers on the calculator. The
register R1 stores the value of the operation result of the latest operation; the register R2 stores the new
input value; and the register R3 stores the input operator. At the beginning, both R1 and R2 hold zero,
and R3 holds a null operator. The calculator has keys for decimal digits from ‘0’ to ‘9’ and operators
‘+’, ‘-’, ‘×’ and ‘=’. The four operators indicate addition, subtraction, multiplication and conclusion,
respectively. When a digit key is pressed, R2 is multiplied by ten, and then added by the pressed digit
(as a number). When ‘+’, ‘-’ or ‘×’ is pressed, the calculator first applies the binary operator held in R3
to the values in R1 and R2 and updates R1 with the result of the operation. Suppose R1 has 10, R2 has
3, and R3 has ‘-’ (subtraction operator), R1 is updated with 7 ( = 10 - 3). If R3 holds a null operator,
the result will be equal to the value of R2. After R1 is updated, R2 is cleared to zero and R3 is set to the
operator which the user entered. ‘=’ indicates termination of a computation. So, when ‘=’ is pressed,
the calculator applies the operator held in R3 in the same manner as the other operators, and displays the
final result to the user. After the final result is displayed, R3 is reinitialized with a null operator.

The calculator cannot handle numbers with five or more decimal digits. Because of that, if the intermediate computation produces a value less than 0 (i.e., a negative number) or greater than 9999, the calculator
displays “E” that stands for error, and ignores the rest of the user input until ‘=’ is pressed.

Your task is to write a program to simulate the simple calculator.

Input

The input consists of multiple test cases.

Each line of the input specifies one test case, indicating the order of key strokes which a user entered.
The input consists only decimal digits (from ‘0’ to ‘9’) and valid operators ‘+’, ‘-’, ‘*’ and ‘=’ where ‘*’
stands for ‘×’.

You may assume that ‘=’ occurs only at the end of each line, and no case contains more than 80 key
strokes.

The end of input is indicated by EOF.

Output

For each test case, output one line which contains the result of simulation.

Sample Input

1+2+3+4+5+6+7+8+9+10=
1000-500-250-125=
1*2*3*4*5*6=
5000*5000=
10-100=
100*100=
10000=

Output for the Sample Input

55
125
720
E
E
E
E


object Main extends App {

  import scala.io.StdIn._
  import scala.math._

  val Array(n, s) = readLine.trim.split(' ').map(_.toInt)
  val planets = Array.tabulate(n){i ⇒
    val Array(l, r) = readLine.trim.split(' ').map(_.toInt)
    Time(l, r)
  }
  val distance = Array.tabulate(n){_ ⇒ readLine.trim.split(' ').map(_.toInt)}
  for (i ← planets.indices){
    if (planets(i).from < distance(s - 1)(i))
      planets(i) = planets(i).copy(from = distance(s - 1)(i))
  }
  val maxTime = Array.tabulate(n){_ ⇒ 0L}
  for ((p, i) ← planets.zipWithIndex.sortBy(_._1.to)){
    if (p.to >= p.to) {
      if (maxTime(i) < p.to - p.from)
        maxTime(i) = p.to - p.from
      for ((q, j) ← planets.zipWithIndex if i != j) {
        if (q.to + distance(j)(i) <= p.from) {
          if (maxTime(i) < maxTime(j) + p.to - p.from)maxTime(i) = maxTime(j) + p.to - p.from
        } else if (q.to + distance(j)(i) <= p.to) {
          if (maxTime(i) < maxTime(j) + p.to - q.to - distance(j)(i)) maxTime(i) = maxTime(j) + p.to - q.to - distance(j)(i)
        }
      }
    }
  }
  println(
    maxTime.max
  )
  case class Planet(id: Int, time: Time)
  case class Time(from: Int, to: Int)
}

F - ７歳教

７歳の誕生日に"彼"は父から告げられた．

「お前が７歳になったということは，私はもう引退だ．今日からお前が７歳教の長だ．

７歳教の戒律により，７歳教の長が７歳の間だけ布教活動を行うことが認められている．

この宇宙船を使って，よりたくさんの人々に７歳教の素晴らしさを広めてきなさい．」

７歳教をよりたくさんの人に広めるために"彼"は，自分の周りの星についての情報を集めた．

"彼"の星の周りには，n 個の惑星があり，惑星は 1, ... , n で番号付けされていることがわかった．

惑星i から 惑星jの間を移動するには，w_i_j (年)の時間がかかることもわかった．

そして，それぞれの星で彼が７歳でいられる時間，つまり布教活動できる時間が異なることがわかった．

それぞれの惑星上では，宇宙暦l_i年1月1日00:00:00以降r_i年1月1日00:00:00より前までの時間帯であれば7歳でいられる．

たとえ一度ある星で７歳以外の年齢になっても，その星で後から７歳になった場合や，別の星で７歳になれば布教活動を再開することができる．

しかしどの星でどれくらい，そしてどの順序で布教活動を行えばより多くの人に７歳教を伝えることができるのか，

"彼"にはわからなかった．そこで"彼"はプログラミングが得意なあなたに助けを求めることにした．

現在は宇宙暦0年1月1日00:00:00であり，"彼"は惑星 s にいる．
惑星間を最適に移動・滞在した場合に布教活動が行える最長の年数，

つまり"彼"が７歳でかつ惑星で過ごす最長の年数Tを求めてあげよう．
ただし，年数Tには移動時間は含まれない．

入力形式

入力は以下の形式で与えられる．

n s
l_1 r_1
...
l_{n} r_{n}
w_{1,1} w_{1,2} ... w_{1,n}
...
w_{n,1} w_{n,2} ... w_{n,n}

n は惑星の個数である．s は主人公が最初にいる惑星をあらわす．

l_i と r_i はそれぞれ，惑星i での7歳でいられる時間帯の下限と上限をあらわす．

w_i_j は，惑星iから惑星jを移動するのにかかる時間をあらわす．

入力はすべて整数である．

出力形式

答えTを出力せよ．

制約

1 ≤ n ≤ 500

1 ≤ s ≤ n

0 ≤ l_i < r_i ≤ 10^8

0 ≤ w_{ij} ≤ 10^8 (i ≠j)

w_{ij} = 0 (i = j)

入出力例

入力例 1

2 1
0 100
150 250
0 100
100 0

出力例 1

150

入力例 2

5 1
7 44
10 49
38 48
11 23
11 30
0 1 7 2 7
10 0 3 8 10
4 8 0 2 5
3 2 1 0 4
8 4 3 3 0

出力例 2

41


//import java.util.Scanner

import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

class IUnionFind(val size: Int) {

  private case class Node(var parent: Option[Int], var treeSize: Int)

  private val nodes = Array.fill[Node](size)(Node(None, treeSize = 1))

  def union(t1: Int, t2: Int): IUnionFind = {
    if (t1 == t2) return this

    val root1 = root(t1)
    val root2 = root(t2)
    if (root1 == root2) return this

    val node1 = nodes(root1)
    val node2 = nodes(root2)

    if (node1.treeSize < node2.treeSize) {
      node1.parent = Some(t2)
      node2.treeSize += node1.treeSize
    } else {
      node2.parent = Some(t1)
      node1.treeSize += node2.treeSize
    }
    this
  }

  def connected(t1: Int, t2: Int): Boolean = t1 == t2 || root(t1) == root(t2)

  def root(t: Int): Int = nodes(t).parent match {
    case None => t
    case Some(p) =>
      nodes(t).parent = Some(root(p))
      nodes(t).parent.get
  }
}

object Main {
  def solve(sc: => Scanner): Unit = {
    val N = sc.nextInt()
    println(
      Array.fill(N)(sc.next()).zip(Array.fill(N)(sc.next()))
        .foldLeft(((0, 0), None: Option[Boolean]))((prev, now) =>
          prev match {
            case (_, Some(_)) => prev
            case (prevV, None) =>
              now match {
                case ("tameru", "tameru") => ((Math.min(5, prevV._1 + 1), Math.min(5, prevV._2 + 1)), prev._2)
                case ("tameru", "mamoru") => ((Math.min(5, prevV._1 + 1), prevV._2), prev._2)
                case ("mamoru", "tameru") => ((prevV._1, Math.min(5, prevV._2 + 1)), prev._2)
                case ("mamoru", "mamoru") => prev
                case ("kougekida", "mamoru") =>
                  if (prevV._1 == 0) (prevV, Some(false))
                  else if (prevV._1 == 5) (prevV, Some(true))
                  else ((0, prevV._2), None)
                case ("mamoru", "kougekida") =>
                  if (prevV._2 == 0) (prevV, Some(true))
                  else if (prevV._2 == 5) (prevV, Some(false))
                  else ((prevV._1, 0), None)
                case ("kougekida", "tameru") =>
                  if (prevV._1 == 0) (prevV, Some(false))
                  else (prevV, Some(true))
                case ("tameru", "kougekida") =>
                  if (prevV._2 == 0) (prevV, Some(true))
                  else (prevV, Some(false))
                case ("kougekida", "kougekida") =>
                  if (prevV._1 == prevV._2) ((0, 0), None)
                  else if (prevV._1 == 0) (prevV, Some(false))
                  else if (prevV._2 == 0) (prevV, Some(true))
                  else if (prevV._1 > prevV._2) ((prevV, Some(true)))
                  else (prevV, Some(false))
              }
          }
        )
        ._2 match {
        case Some(true) => "Isono-kun"
        case Some(false) => "Nakajima-kun"
        case None => "Hikiwake-kun"
      })
  }

  def recursive(now: Long, minV: Long): Set[Long] = {
    if (Math.sqrt(now) < minV) Set(now) else {
      if (now % minV == 0) recursive(now / minV, minV + 1) + minV else recursive(now, minV + 1)
    }
  }

  def time(s: String): Int =
    s.substring(0, 2).toInt * 60 + s.substring(3, 5).toInt

  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def calc(A: Array[Long]): Array[String] = {
    if (A.length == 0) Array.fill(0)("")
    else {
      val last = A.zipWithIndex.map(x => (x._1 - x._2, x._1)).takeWhile(x => x._1 == A.head).last._2
      if (last == A.head) "%d".format(A.head) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
      else "%d-%d".format(A.head, last) +: calc(A.zipWithIndex.map(x => (x._1 - x._2, x._1)).dropWhile(x => x._1 == A.head).map(x => x._2))
    }
  }

  var memo: Map[(Long, Long), Long] = Map[(Long, Long), Long]()

  @scala.annotation.tailrec
  def recursive2(X: Set[Long], Y: Stream[Long]): Long = if (X.contains(Y.head)) X.size else recursive2(X + Y.head, Y.tail)

  def check(i: Int, X: String): Long = {
    if (X == "") 0 else check(i, X.tail) * i + X.head.toString.toLong
  }

  def shift(n: Long): Long = {
    if (n == 0) 0
    else if (n == 1) 1
    else shift(n - 1) << 1
  }

  def unShift(n: Long): Long = {
    if (n == 0) 0
    else unShift(n >> 1) + 1
  }

  @scala.annotation.tailrec
  def gcd(i: Long, j: Long): Long = {
    if (i < j) gcd(j, i)
    else if (j == 0) i
    else gcd(j, i % j)
  }

  def primeFactors(i: Long): List[Long] = primeFactors_(i, 1).sorted

  def primeFactors_(i: Long, j: Long): List[Long] = {
    if (j * j > i) List.empty else if (i % j == 0) primeFactors_(i, j + 1) ++ List[Long](j, i / j) else primeFactors_(i, j + 1)
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    solve(sc)
  }
}

object Util {
  def getPermutation(begin: Long = 0): Stream[Long] =
    Stream.cons(begin, getPermutation(begin + 1))

  def getPrimeList: Stream[Long] =
    getPrimeListRecursive(getPermutation(begin = 2))

  private def getPrimeListRecursive(A: Stream[Long]): Stream[Long] =
    Stream.cons(A.head, getPrimeListRecursive(A.tail.filter(_ % A.head != 0)))

  def fib(a: Long = 0, b: Long = 1, mod: Long = Long.MaxValue): Stream[Long] = a #:: fib(b % mod, (a + b) % mod, mod)
}

object ArabicRoman {

  type =?>[A, B] = PartialFunction[A, B]

  val codeTable = List(
    (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
    (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"))

  val arabicToRoman: Int =?> String = {
    case src if src >= 1 && src <= 3999 =>

      @scala.annotation.tailrec
      def convert(left: Int, cont: String = "", code: List[(Int, String)] = codeTable): String = {
        val (unitVal, unitChar) = code.head
        left - unitVal match {
          case n if n == 0 => cont + unitChar
          case n if n > 0 => convert(n, cont + unitChar, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src)
  }

  val romanToArabic: String =?> Int = {
    case src if Option(src).exists { s => {
      s.nonEmpty && """[^MDCLXVI]""".r.findFirstMatchIn(s.toUpperCase).isEmpty
    }
    } =>

      @scala.annotation.tailrec
      def convert(left: String, cont: Int = 0, code: List[(Int, String)] = codeTable): Int = {
        val (unitVal, unitChar) = code.head
        left.splitAt(unitChar.length) match {
          case ("", _) => cont
          case (`unitChar`, tail) => convert(tail, cont + unitVal, code)
          case _ => convert(left, cont, code.tail)
        }
      }

      convert(src.toUpperCase())
  }
}

A: 磯野、あれやろうぜ！ - Sendame -

物語

中島「磯野〜，あれやろうぜ！」

磯野「あれって何だよ，中島」

中島「ほら，あれだよ，あれ．なぜか文字で表さなきゃならないから，説明しづらいな〜」

磯野「いや，図や写真も入れられるみたいだぞ？」

中島「本当だ！」

磯野「で，何をやるんだ？」

中島「ほら，リズムに乗って，手を2回叩いた後に，防御，溜め，攻撃のポーズを取るやつ」

磯野「う〜ん，イマイチわからないな…」

中島「2回手を叩いた後に，例えば防御だったら」

中島「で，溜めだったら」

中島「攻撃だったら」

中島「ってやるやつ，知ってるだろ？」

磯野「ああ！写真が入ると劇的に分かりやすくなるな！」

中島「これぞ文明の進歩だな！」

(それから悠久の時が経った)

花沢「い゛そ゛の゛く゛〜゛ん゛な゛か゛じ゛ま゛く゛〜゛ん゛」

二人「(パチパチ…パチパチ…パチパチ…)」

花沢「アンタたち，まさか寝ながらあれやってるの…！？」

花沢「今勝負ついたじゃない…磯野くん，今あなた勝ったわよ？」

磯野「……花沢さん来てたんだ…中島もう一度やるぞ…zzz」

中島「(こくり)」

二人「(パチパチ…パチパチ…)」

花沢「もう…ここに，あれの勝敗判定ロボット置いておくから…」

そうして花沢さんは去って行った．

ということがあるかもしれないので，あれの勝敗判定プログラムを書いてください．

問題

「あれ」は2人で行うゲームである．リズムに合わせて2人が同時に，防御，溜め，攻撃のいずれかのポーズを取ることを繰り返す．ここで，2人がポーズを取るタイミングのことを「回」と表記する．このゲームでは，ある回で勝敗がつき，かつ，それまでの回で勝敗がついていないとき，その勝敗がゲームの勝敗となる．

2人はそれぞれ「攻撃力」というパラメータを持ち，ゲーム開始時，攻撃力は 0 である．

攻撃のポーズを取った場合，その時点での攻撃力に応じて，次のようになる．

攻撃力が 0 のときに攻撃のポーズを取ると，反則負けとなる．ただし，相手も攻撃力が 0 で攻撃のポーズをした場合，その回では勝敗がつかない．

自分の攻撃力が 1 以上のときに攻撃のポーズをとると，相手に攻撃を加える．また，その回で相手も攻撃のポーズを取った場合，攻撃力のより高いプレイヤーが勝利する．ただし，両プレイヤーが同じ攻撃力で攻撃のポーズを取った場合には，その回では勝敗がつかない．

また，攻撃のポーズを取った回の終了時に，自分の攻撃力が 0 になる．

溜めのポーズを取ると，そのプレイヤーの攻撃力が 1 だけ上昇する．ただし，攻撃力が 5 である場合，そのプレイヤーが溜めのポーズを取っても，攻撃力は 5 のままである．溜めのポーズを取った回で，相手が攻撃を加えた場合，相手が勝利する．なお，溜めのポーズを取った回で，相手が攻撃以外のポーズをとった場合，勝敗がつかない．

防御のポーズを取った回に，相手が攻撃力 5 の攻撃を加えた場合，相手が勝利する．一方，防御のポーズを取った回に，相手が攻撃力 4 以下の攻撃を加えた場合や，溜めまたは防御のポーズを取った場合，その回では勝敗がつかない．なお，防御のポーズを取っても，そのプレイヤーの攻撃力に変化はない．

両プレイヤーのポーズが順に与えられるので，勝敗を出力せよ．なお，両プレイヤーは勝敗が決定した後もポーズをとり続けることがあるが，勝敗が決定した後のポーズは無視するものとする．

入力形式

入力は以下の形式で与えられる．

K
I_1
...
I_K
N_1
...
N_K

入力の1行目には，1個の整数 K ( 1 ≤ K ≤ 100) が与えられる．
2行目からの K 行には，磯野が取ったポーズ I_i (1 ≤ i ≤ K) が順に与えられる．
その直後の K 行には，中島が取ったポーズ N_i (1 ≤ i ≤ K) が順に与えられる．
I_i および N_i は “mamoru”, “tameru”, “kougekida” のいずれかである．これらの文字列は順に，防御，溜め，攻撃のポーズを表す．

出力形式

磯野が勝利した場合には “Isono-kun” ，中島が勝利した場合には “Nakajima-kun” ， K 回で勝敗がつかない場合には， “Hikiwake-kun” と1行で出力せよ．

入力例1

3
tameru
tameru
tameru
tameru
kougekida
tameru

出力例1

Nakajima-kun

2 回目で，磯野が溜めのポーズをしているのに対し，中島は攻撃力 1 の攻撃をしているので，中島の勝利です．

入力例2

3
mamoru
mamoru
mamoru
tameru
tameru
tameru

出力例2

Hikiwake-kun

どちらも攻撃をしなかったので，勝敗がつきませんでした．

入力例3

5
tameru
tameru
mamoru
mamoru
kougekida
tameru
tameru
kougekida
tameru
kougekida

出力例3

Isono-kun

1 回目から 4 回目まででは勝敗がつきません． 5 回目で，両プレイヤーが攻撃のポーズをしていますが，磯野の攻撃力が 2 なのに対し，中島の攻撃力が 1 なので，磯野の勝利です．

入力例4

3
kougekida
kougekida
tameru
kougekida
mamoru
kougekida

出力例4

Nakajima-kun

1 回目では，両プレイヤーが攻撃力 0 で攻撃のポーズを取っているので，勝敗がつきません． 2 回目では，磯野のみが攻撃力 0 で攻撃のポーズをとっているので，中島の勝利です．

入力例5

8
tameru
mamoru
tameru
tameru
tameru
tameru
tameru
kougekida
tameru
kougekida
mamoru
mamoru
mamoru
mamoru
mamoru
mamoru

出力例5

Isono-kun

2 回目では，中島が攻撃力 1 で攻撃のポーズを取っていますが，磯野が防御のポーズを取っているので，勝敗がつきません． 7 回目では，磯野が攻撃力 5 で溜めのポーズを取っているので，磯野の攻撃力は 5 のままです． 8 回目では，磯野が攻撃力 5 で攻撃のポーズをとり，中島が防御のポーズを取っているので，磯野が勝利します．


import scala.collection.mutable.Queue
import io.StdIn

object Main extends App {
  val n = StdIn.readInt
  val seq = StdIn.readLine.split(" ").map(_.toInt % 3)
  val a = for(i <- 0 until 3) yield seq.count(_ == i)

  def bfs(first:Tuple5[Int,Int,Int,Int,Int]):Int = {

    val que = new Queue[Tuple5[Int,Int,Int,Int,Int]]
    que += first
    var cur = (0,0,0,0,0)

    var isCnt = true
    while(isCnt || !que.isEmpty) {
      cur = que.dequeue

      if(cur._2 == 0 || (cur._3 == 0 && cur._4 == 0 && cur._5 == 0)) isCnt = false
      else {
        cur match {
          case (acc, 1, c0, c1, c2) if c0 != 0 => que += {(acc+1, 1, c0-1, c1, c2)}
          case (acc, 2, c0, c1, c2) if c0 != 0 => que += {(acc+1, 2, c0-1, c1, c2)}
          case (acc, 1, c0, c1, c2) if c1 != 0 => que += {(acc+1, 2, 0, c1-1, c2)}
          case (acc, 2, c0, c1, c2) if c2 != 0 => que += {(acc+1, 1, 0, c1, c2-1)}
          case (acc, 2, c0, c1, c2) if c1 != 0 => que += {(acc+1, 0, 0, c1-1, 0)}
          case (acc, 1, c0, c1, c2) if c2 != 0 => que += {(acc+1, 0, 0, 0, c2-1)}
        }
      }
    }
    cur._1
  }

  val res1 = bfs(0,1,a(0),a(1)-1,a(2)) + 1
  val res2 = bfs(0,2,a(0),a(1),a(2)-1) + 1
  val ans = if(a.drop(1).sum == 0) 1 else math.max(res1,res2)
  println(ans)
}

C : Mod!Mod!

物語

じゃん！探してますよ目撃証言！
会津に怪盗が現れた！みんなのウマウマ棒が盗まれた！犯人は誰だ！？
解きあかせ！Mod!Mod!

問題文

"アイズ"...それは選ばれし者の心に膨らむ奇跡のつぼみ...。特殊能力"アイズ"を使えばどんなものだって盗むことができる。

会津一の大怪盗、あいずまるは世界を謎で満たすためにn人の探偵から「ウマウマ棒」を盗むことにした。ウマウマ棒とはあいずまるが大好きなただのお菓子であり、n人の探偵はそれぞれ数本のウマウマ棒を持っている。また、あいずまるは強欲なためそれぞれの探偵からウマウマ棒を盗むとき、その探偵が所持する全てのウマウマ棒を盗む。

ウマウマ棒の3本同時食いにハマっているあいずまるは、3本以上のウマウマ棒が手元にあるとき、誘惑に負けて手持ちのウマウマ棒が3本未満になるまで、3本ずつウマウマ棒を食べてしまう。しかし、あいずまるは手元にウマウマ棒がないとショックでアイズを失ってしまい、それ以上ウマウマ棒を盗むことができなくなってしまう。つまり、ウマウマ棒を盗むためには手持ちのウマウマ棒の本数を1本以上にしておく必要があり、0本になるとそれ以上ウマウマ棒を盗むことができなくなる。

少しでも多くの探偵からウマウマ棒を盗みたいあいずまるは、どの探偵から順にウマウマ棒を盗むかによって何人の探偵からウマウマ棒を盗めるのかが変わることに気づいた。しかし、あいずまるには難しいことは分からない。「ハテー？」あいずまるの優秀な部下であるあなたは、あいずまるの代わりに最大で何人の探偵からウマウマ棒を盗むことができるのかを求めるプログラムを書いてあげることにした。

探偵の人数nと、n人の探偵からそれぞれ何本のウマウマ棒を盗むのかが与えられるので、最適な順番で探偵からウマウマ棒を盗んだとき、最大で何人の探偵からウマウマ棒を盗むことができるかを出力するプログラムを作成せよ。ただし、はじめの手持ちのウマウマ棒の本数は0であるが、最初に限り手持ちが0本でもウマウマ棒を盗むことができるとする。

入力形式

入力は2行からなり、以下の形式で与えられる。

n
a_1 a_2 … a_n

1行目には、ウマウマ棒を盗む探偵の数である整数nが与えられる。
2行目には、各探偵から盗むウマウマ棒の本数n個が空白区切りで与えられる。

制約

1 ≤ n ≤ 500{,}000

1 ≤ a_i ≤ 9 (1 ≤ i ≤ n)

出力形式

最適な順番で探偵からウマウマ棒を盗んだとき、最大で何人の探偵からウマウマ棒を盗むことができるか一行に出力せよ。

入力例1

6
2 5 2 5 2 1

出力例1

5

2 5 1 2 5の順で盗むと5人から盗むことができる。どのような順序で盗んでも6人から盗むことはできない。

入力例2

3
3 6 9

出力例2

1

どの1人から盗んでも手持ちのウマウマ棒の本数は0になってしまい、アイズを失ってしまう。

入力例3

6
1 2 3 4 5 6

出力例3

6


import java.util.Scanner

object Main {
  def solve(sc: => Scanner): Long = {
    val N, K = sc.nextInt
    val A = Array.fill(N)(sc.nextInt - 1)
    val Ans = A.map(X => X == -1)
    val leaf = Array.fill(N)(true)
    for (i <- 0 until N) {
      if (A(i) != -1) (leaf(A(i)) = false)
    }
    var i = 0
    while (i < N) {
      if (leaf(i)) {
        var now = i
        var idx = 0
        while (idx < K && A(now) != -1) {
          Ans(now) = true
          if (A(now) != -1) (now = A(now))
          idx += 1
        }
      }
      i += 1
    }
    Ans.filter(x => x).length
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)

    println(solve(sc))
  }
}

MathJax.Hub.Config({ tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]} });

C: ツイート数

問題

AORイカちゃんが利用するSNSであるイカったーでは、投稿のことをツイートと呼ぶ。

そして、イカったーでは、ツイートへの返信が多くなると視認性が悪くなることが懸念されるため、あるツイートが次の規則のいずれかを満たすときに画面にそのツイートを表示する仕様になっている。

規則１. どのツイートへも返信していない

規則２. どのツイートからも返信されていない

規則３. 規則２が適用されたツイートから返信先を順に辿ったとき、 $K$ 回未満で辿り着ける

なお、同じツイートは重複して表示されることはない。

いま、 $N$ 個のツイートがあり、 $A_i$ が $0$ のとき $i$ 番目のツイートは返信でないツイートで、 $A_i$ が $0$ でないとき $i$ 番目のツイートは $A_i$ 番目のツイートへの返信のツイートである。

画面に表示されるツイート数を答えよ。

制約

$1 \le N \le 10^5$

$1 \le K \le 10^5$

$0 \le A_i \lt i (i = 1, 2, \dots, N)$

ツイートは時系列順に与えられる。

入力は全て整数で与えられる。

入力形式

入力は以下の形式で与えられる。

$N \ K$
$A_1$
$A_2$
$\vdots$
$A_N$

出力

画面に表示されるツイート数を出力せよ。また、末尾に改行も出力せよ。

サンプル

サンプル入力 1

6 3
0
0
2
3
4
5

サンプル出力 1

5

この時、表示されるツイートは、図の青いツイートである。 よって、この例の解は $5$ である。

サンプル入力 2

12 2
0
1
0
3
4
3
6
7
0
9
10
11

サンプル出力 2

10

サンプル入力 3

5 10
0
0
0
0
0

サンプル出力 3

5


object Main extends App {

  import scala.io.StdIn._
  import scala.math._

  val Array(n, m, q) = readLine.trim.split(' ').map(_.toInt)
  val floors = SegTree(1, n)
  for (_ ← 0 until m) {
    val Array(d, a, b) = readLine.trim.split(' ').map(_.toInt)
    floors.setUpperLimit(a, b - 1, d)
  }
  for (_ ← 0 until q){
    val Array(e, s, t) = readLine.trim.split(' ').map(_.toInt)
    val day = floors.maxBetween(s, t - 1)
    println(
      if (day < e) "Yes"
      else "No"
    )
  }
  object SegTree{
    def apply(from: Int, to: Int, default: Int = Int.MaxValue): SegTree = {
      if (from == to) new Leaf(default, from)
      else new Node(from, to, SegTree(from, (from + to) / 2, default), SegTree((from + to) / 2 + 1, to, default))
    }
  }
  sealed trait SegTree{
    def maxBetween(from: Int, to: Int): Int
    def setUpperLimit(from: Int, to: Int, limit: Int): Unit
    def upper: Int
  }
  class Node(private val mFrom: Int, private val mTo: Int, private val mLeft: SegTree, private val mRight: SegTree) extends SegTree {
    override def upper: Int = mUpper
    private var mUpper = math.max(mLeft.upper, mRight.upper)

    override def setUpperLimit(from: Int, to: Int, limit: Int): Unit = {
      if (mUpper > limit) {
        if (from <= mFrom && mTo <= to) {
          mUpper = limit
        } else if (from <= mTo && mFrom <= to) {
          mLeft.setUpperLimit(mFrom, mTo, mUpper)
          mLeft.setUpperLimit(from, to, limit)
          mRight.setUpperLimit(mFrom, mTo, mUpper)
          mRight.setUpperLimit(from, to, limit)
          mUpper = math.max(mLeft.upper, mRight.upper)
        }
      }
    }
    override def maxBetween(from: Int, to: Int): Int = {
      if (to < mFrom || mTo < from) Int.MinValue
      else if (from <= mFrom && mTo <= to) mUpper
      else {
        mLeft.setUpperLimit(mFrom, mTo, mUpper)
        mRight.setUpperLimit(mFrom, mTo, mUpper)
        math.max(mLeft.maxBetween(from, to), mRight.maxBetween(from, to))
      }
    }
  }
  class Leaf(private var mValue: Int, private val mPosition: Int) extends SegTree {
    override def maxBetween(from: Int, to: Int): Int = {
      if ((from to to).contains(mPosition)) mValue
      else Int.MinValue
    }

    override def setUpperLimit(from: Int, to: Int, limit: Int): Unit = {
      if ((from to to).contains(mPosition) && limit < mValue) mValue = limit
    }

    override def upper: Int = mValue
  }
  implicit class Extension[T](val value :T){
    def also(func: T ⇒ Unit): T = {
      func(value)
      value
    }
    def let[R](func: T ⇒ R): R = func(value)
  }
}

G: エレベータ

問題

株式会社AORは $N$ 階建てのビルである。地下階は存在しない。

AORイカちゃんはイカであるため、階段を下りることは可能だが、上ることは不可能である。

上の階に登れないと不便なため、$M$ 個のエレベータをビルに設置することにした。

エレベータを設置するには時間がかかり、$i$ 番目のエレベータは $D_i$ 日後の夜に設置が完了し、 $A_i$ 階以上 $B_i$ 階以下の全ての階を移動可能にする。

あなたはAORイカちゃんに $Q$ 個の質問をされた。$i$ 番目の質問は「 $E_i$ 日後の昼に、$S_i$ 階から $T_i$ 階に移動可能か？」という質問である。

移動に使える手段は階段とエレベータのみである。また移動にかかる時間は無視できるものとする。

制約

$2 \le N \le 10^5$

$1 \le M \le 10^5$

$1 \le Q \le 10^5$

$1 \le D_i , E_i \le 10^9$

$1 \le A_i < B_i \le N$

$1 \le S_i , T_i \le N$

入力は全て整数

入力

$N \ M\ Q$

$D_1 \ A_1 \ B_1$

$\vdots$

$D_M \ A_M \ B_M$

$E_1 \ S_1 \ T_1$

$\vdots$

$E_Q \ S_Q \ T_Q$

出力

各質問ごとに一行で Yes または No を出力せよ。ただし質問された順に答えること。また末尾に改行を出力せよ。

サンプル

サンプル入力 1

5 1 2
3 1 5
3 1 5
4 1 5

サンプル出力 1

No
Yes

エレベータが設置されるのは三日目の夜であるため、三日目の昼に移動することはできない。

サンプル入力 2

8 6 5
30 6 7
21 3 8
5 2 4
10 1 2
2 7 8
15 5 7
16 5 8
11 1 3
22 3 7
30 6 7
15 5 8

サンプル出力 2

Yes
Yes
Yes
Yes
No


object Main extends App {
  import scala.io.StdIn._

  println(
    if (readLine.trim == "ani") "square1001" else "e869120"
  )
  implicit class Scope[T](val value: T) extends AnyVal {
    @inline
    def let[A](func: T ⇒ A): A = func(value)
  }
}

B: 双子 (Twins)

とある双子は、自分たちのどちらが兄でどちらが弟かがあまり知られていないことに腹を立てた。

"ani" と入力されたら "square1001"、"otouto" と入力されたら "e869120" と出力するプログラムを作りなさい。

入力

入力として "ani" または "otouto" という文字列のどちらかが与えられます。

出力

"e869120" または "square1001" を、問題文の通りに出力してください。最後の改行を忘れないようにしましょう。

入力例1

ani

出力例1

square1001

入力例2

otouto

出力例2

e869120


object Main extends App {
  import scala.io.StdIn._

  val Array(n, a, b, c) = readLine.trim.split(' ').map(_.toInt)
  println(
    n - a - b + c
  )
  implicit class Scope[T](val value: T) extends AnyVal {
    @inline
    def let[A](func: T ⇒ A): A = func(value)
  }
}

E-修行

ねねさんはプログラミングの修行のため、$N$ 個の整数 $V_1, V_2, V_3, \cdots, V_N$ について調べるプログラムを作っている。

指導役のうみこさんに言われて、ねねさんは 2, 3, 6 の倍数の個数を調べるプログラムを書いた。

2 の倍数は $A$ 個、3 の倍数は $B$ 個、6 の倍数は $C$ 個だった。

うみこさんは、次は「2 の倍数でも 3 の倍数でもない数」の個数を調べるようにと言った。

しかし、ねねさんは疲れたので、答えだけを求めてごまかすことにした。

$N, A, B, C$ の値だけをもとに、「2 の倍数でも 3 の倍数でもない数」の個数が分かります。これを求めるプログラムを作ってください。

入力

$N, A, B, C$ が空白区切りで与えられる。

出力

データの中にある「2 の倍数でも 3の倍数でもない数」の個数を出力せよ。ただし、最後には改行を入れること。

制約

$N$ は $1$ 以上 $100$ 以下の整数

$A, B, C$ は $0$ 以上 $N$ 以下の整数

$A$ が $N$ より大きいなどという、矛盾するデータは与えられない

入力例1

6 3 2 1

出力例1

2

例えばデータが $2, 3, 4, 5, 6, 7$ のときは、$5$ と $7$ のふたつが「2 の倍数でも 3 の倍数でもない数」です。

入力例2

10 9 9 9

出力例2

1


import java.io._
import java.nio.file.Files._
import java.nio.file.Path
import java.util.StringTokenizer

import scala.collection.immutable._
import scala.io.Codec
import scala.collection.Searching._

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

class Scanner(reader: LineNumberReader) extends Iterable[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))

  def this(reader: Reader) = this(new BufferedReader(reader))

  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

  def this(path: Path)(implicit codec: Codec) = this(newBufferedReader(path, codec.charSet))

  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

  def this(str: String) = this(new StringReader(str))

  override def iterator: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext: Boolean = current.hasNext

  @inline def next(): String = current.next()

  /**
    * This is different from Java's scanner.nextLine
    * The Java one is a misnomer since it actually travel to end of current line
    * This one actually does fetch the next line
    */
  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }

  def lineNumber: Int = reader.getLineNumber

  def nextString(): String = next()

  def nextBoolean(): Boolean = next().toBoolean

  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

  def nextFloat(): Float = next().toFloat

  def nextDouble(): Double = next().toDouble

  def nextBigDecimal(): BigDecimal = BigDecimal(next())

  override def close(): Unit = reader.close()
}

object Main {

  def solve(sc: => Scanner): Unit = {
    val N, M = sc.nextInt()
    val A = Array.fill(N)(sc.nextLong()).sorted
    val sumOfA = A.scanLeft(0L)((a, b) => a + b)

    println(Array.fill(M)(sc.nextLong()).map(b => b).sum)

  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)
    solve(sc)
  }
}

N: 通販 (Mail Order)

胡桃沢さんは、魔界通販で積み木のおもちゃを買った。

積み木は一辺の長さが1の立方体の形をしており、縦に $H$ 個、横に $W$ 個に分割されたマス目の上に積まれている。

真横から見ると、左から順に、$A_1, A_2, A_3, \dots, A_H$ 個のブロックが積まれて見えた。

正面から見ると、左から順に、$B_1, B_2, B_3, \dots, B_W$ 個のブロックが積まれて見えた。

胡桃沢さんは偉大なので、これらの情報だけからブロックの総数を当てようと考えた。

小さい数を答えて間違えると格好悪いので、考えられる最大の個数を答えたい。

入力

1 行目には整数 $H, W$ が空白区切りで与えられる。

2 行目には、真横から見たときの図を表す $H$ 個の整数 $A_1, A_2, A_3, \dots, A_H$ が空白区切りで与えられる。

3 行目には、正面から見たときの図を表す $W$ 個の整数 $B_1, B_2, B_3, \dots, B_W$ が空白区切りで与えられる。

出力

これらの情報から考えられるブロックの個数の最大値を出力しなさい。

制約

$H, W$ は $1$ 以上 $100 \ 000$ 以下の整数

$A_1, A_2, A_3, \dots, A_H$ は $1$ 以上 $100 \ 000 \ 000$ 以下の整数

$B_1, B_2, B_3, \dots, B_W$ は $1$ 以上 $100 \ 000 \ 000$ 以下の整数

すべての入力に対して、条件を満たすブロックの積み方があることが保証される

入力例1

2 2
1 5
1 5

出力例1

8

縦方向に $X$ 番目、横方向に $Y$ 番目のマスを $(X, Y)$ で表すことにします。

マス $(2, 2)$ に5個、マス $(1, 1)$、$(1, 2)$、$(2, 1)$ に $1$ 個ずつ積まれていると合計 $8$ 個のブロックが積まれることになります。

$9$ 個以上積まれている可能性は無いので、答えは $8$ です。

入力例2

3 3
2 4 5
3 1 5

出力例2

22


import java.util.Scanner

object Main {
  def solve(sc: => Scanner): Unit = {
    val A, B = sc.nextDouble
    val N = (A - B) / -2 + 360 + A
    println(N % 180)
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)

    solve(sc)
  }
}

Problem A: The Mean of Angles

Problem

与えられた2つの角度θ1,θ2 のちょうど間の角度を求めよ。ここで、ちょうど間の角度を、下図のように「θ1 + t = θ2 − t を満たすtのうち絶対値が最も小さいものをt’としたときのθ1 + t’」と定義する。

Input

入力は以下の形式で与えられる。

θ1
θ2

Constraints

入力は以下の条件を満たす。

角度は度数法(degree)で表される

0 ≤ θ1, θ2 < 360

θ1, θ2は整数

|θ1 − θ2| ≠ 180

解答が[0,0.0001]または[359.999, 360)になるような入力は与えられない

Output

θ1,θ2のちょうど間の角度を度数法で[0,360)の範囲で1行に出力せよ。ただし0.0001を超える誤差を含んではならない。

Sample Input 1

10
20

Sample Output 1

15.0

Sample Input 2

20
350

Sample Output 2

5.0


import java.util.Scanner

object Main {
  def solve(sc: => Scanner): Unit = {
    val A, B = sc.nextDouble
    val N = (math.max(A, B) - math.min(A, B)) / 2 + math.min(A, B)
    println(if (A - N < 90) (N) else {
      if (N + 180 >= 180) (N - 180) else (N + 180)
    })
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)

    solve(sc)
  }
}


import java.util.Scanner

object Main {
  def solve(sc: => Scanner): Unit = {
    val A, B = sc.nextDouble
    val N: Double = (math.max(A, B) - math.min(A, B)) / 2 + math.min(A, B)
    println(if (A - N < 90) (N) else {
      if (N + 180 >= 360) (N - 180) else (N + 180)
    })
  }

  def main(args: Array[String]): Unit = {
    val sc: Scanner = new Scanner(System.in)

    solve(sc)
  }
}


import java.util.Scanner

object Main extends App {
  val in = new Scanner(System.in)
  val N = in.nextInt()
  val L = in.nextInt()
  val K = in.nextLong()
  val ad: Array[(Long, Long)] = (for (_ <- 0 until N) yield {
    val a: Long = in.nextInt()
    val d: Long = in.nextInt()
    (a, d)
  }).toArray

  val sum = ad.map {
    case (a, d) => (a + (a + (L - 1) * d)) * L / 2
  }

  // imos[i+1] = sum(0...i)
  val imos = new Array[Long](N + 1)
  for (i <- 0 until N) {
    imos(i + 1) = imos(i) + sum(i)
  }

  def calc(a0: Long, da: Long, b0: Long, db: Long, p: Int): Long = {
    def value(x: Int): Long = (b0 - a0) * x + x * (x - 1) * (db - da) / 2

    val left = 0
    val right = value(p)
    if (db - da >= 0) {
      math.max(left, right)
    } else {
      val y = b0 - a0
      val z = db - da
      var t = (z - 2 * y).toDouble / 2 / z
      t = math.max(t, 0)
      t = math.min(t, p)
      math.max(value(math.ceil(t).toInt), value(math.floor(t).toInt))
    }
  }

  if (K == N * L) {
    println(imos(N))
  } else {
    val ans = (for {
      head <- 0 until N
      if head + K / L < N
    } yield {
      val a0 = ad(head)._1
      val da = ad(head)._2

      val idx = (head + K / L).toInt
      val rest = (K % L).toInt
      val p = L - rest

      val b0 = ad(idx)._1 + rest * ad(idx)._2
      val db = ad(idx)._2

      val sum1 = imos(idx) - imos(head) + (ad(idx)._1 + ad(idx)._1 + (rest - 1) * db) * rest / 2
      val sum2 = calc(a0, da, b0, db, p) + sum1

      if (idx + 1 < N && rest >= 2) {
        val sum3 = sum1 + (b0 + b0 + (p - 1) * db) * p / 2 - (a0 + a0 + (p - 1) * da) * p / 2

        val c0 = ad(idx + 1)._1
        val dc = ad(idx + 1)._2

        val ax = a0 + p * da

        val sum4 = calc(ax, da, c0, dc, rest) + sum3

        math.max(sum2, sum4)
      } else {
        sum2
      }
    }).max
    println(ans)
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Problem H: Sequence

Problem

項数$L$の等差数列が$N$個ある。$i$番目の等差数列の初項は$a_i$で公差は$d_i$である。1番目の数列から順番に1番目の数列, 2番目の数列, ..., $N$番目の数列と並べ、そうしてできた数列を$A$とする。その後、$A$から長さ$K$の任意の区間を選んで、新たに数列$B$を作るとき、数列$B$の和を最大化せよ。

Input

入力は以下の形式で与えられる。

$N$ $L$ $K$

$a_1$ $d_1$

$a_2$ $d_2$

...

$a_N$ $d_N$

1行目に3つの整数$N$, $L$, $K$が空白区切りで与えられる。

続く$N$行に、$i$個目の等差数列の情報$a_i$, $d_i$が空白区切りで与えられる。

Constraints

入力は以下の条件を満たす。

$1 \leq N \leq 10^5$

$1 \leq L \leq 10^5$

$1 \leq K \leq N\times L$

$0 \leq a_i \leq 10^5$

$1 \leq d_i \leq 10^3$

入力はすべて整数

Output

数列$B$の和の最大値を1行に出力する。

Sample Input 1

3 3 5
0 3
2 2
4 1

Sample Output 1

25

数列$A$は$0,3,6,2,4,6,4,5,6$となる。この数列の第5項から第9項までを数列$B$とすれば、数列$B$の和は25となり、これが最大である。

Sample Input 2

3 3 5
0 10
8 1
11 1

Sample Output 2

58


object Main extends App {
  import scala.io.StdIn._
  val n = readInt()
  val crypt = readLine.trim
  val coordinate = crypt.foldLeft(Coordinate(0, 0)){
    case (pos, c) if 'A' to 'M' contains c ⇒ pos.copy(y = pos.y - 1)
    case (pos, c) if 'N' to 'Z' contains c ⇒ pos.copy(y = pos.y + 1)
    case (pos, c) if 'a' to 'm' contains c ⇒ pos.copy(x = pos.x + 1)
    case (pos, c) if 'n' to 'z' contains c ⇒ pos.copy(x = pos.x - 1)
    case _ ⇒ ???
  }
  println(math.abs(coordinate.x) + math.abs(coordinate.y))
  println(encrypt(coordinate))

  case class Coordinate(x: Int, y: Int) {
    def +(that: Coordinate): Coordinate = Coordinate(x + that.x, y + that.y)
  }
  def encrypt(coordinate: Coordinate): String = {
    coordinate match {
      case Coordinate(x, y) if x >= 0 && y >= 0 ⇒ "N" * y + "a" * x
      case Coordinate(x, y) if x >= 0 ⇒ "A" * -y + "a" * x
      case Coordinate(x, y) if x < 0 && y < 0 ⇒ "A" * -y + "n" * -x
      case Coordinate(x, y) ⇒ "N" * y + "n" * -x
    }
  }
}

B: Shortest Crypt

問題

xryuseixくんの学校では暗号が流行している. 格子状の街に住んでいるxryuseixくんは集合場所を決める新しい暗号を考えた.

暗号文は $N$ 文字の文字列 $S$ からなり, $S_i$ の文字によって現在地からの移動方向を決める. 移動方向に関しては以下の通りである.

A ~ M : 北に１マス進む.

N ~ Z : 南に１マス進む.

a ~ m : 東に１マス進む.

n ~ z : 西に１マス進む.

さて,ここでxryuseixくんは, yryuseiyちゃんにデートの集合場所を暗号文で教えようと思ったのだが, 暗号文が冗長なことに気づいた.

例えば,「ANA」という暗号文があったとしよう. これは北に $1$ マス進み, 南へ $1$ マス進んだのち北へ $1$ マス進む.
これは北に $1$ マス進む暗号文と等価なので,「ANA」＝「A」と, 簡潔にできる. xryuseixくんはyryuseiyちゃんに遠回りをさせないよう,暗号文を簡潔にしようと思った.

そこであなたはxryuseixくんに変わって, 暗号文を簡潔にするプログラムを書くことになった.
なお, 「暗号文を簡潔にする」とは,「元の暗号文と同じ目的地へ行く最も短い暗号文を作る」ということである.

制約

$N$ は整数であり, $S_i$ は大文字または小文字のアルファベットである.

$1 \leq N \leq 10^{5}$

入力形式

入力は以下の形式で与えられる.

$N$

$S$

出力

$1$ 行目に簡潔にした後の暗号文の長さ, $2$ 行目にその暗号文を出力せよ.
答えとしてありうる暗号文が複数存在する場合, どれを出力してもよい.
また各行の末尾に改行を出力せよ.

サンプル

サンプル入力 1

5
ANazA

サンプル出力 1

1
A

サンプル入力 2

7
ACMICPC

サンプル出力 2

5
HIJKL

サンプル入力 3

4
AIZU

サンプル出力 3

0

簡潔にした暗号文(空の文字列)のあとに改行が必要なことに注意.


import scala.io.StdIn.{readInt,readLine}

object Main {
  def max(x:Int,y:Int) = if(x>y) x else y
  def main(args:Array[String]) = {
    val n = readInt

    for(i<-0 until n) {
      val s1 = readLine.trim
      val s2 = readLine.trim
      val maxN = s1.length
      val maxM = s2.length

      val a = Array.ofDim[Int](maxN,maxM)
      for(i<-0 until maxN) if(s1(i)==s2(0)) a(i)(0) = 1
      for(j<-0 until maxM) if(s1(0)==s2(j)) a(0)(j) = 1
      for(i<-1 until maxN) {
        for(j<-1 until maxM) {
          if(s1(i)==s2(j)) {
            a(i)(j) = a(i-1)(j-1)+1
          } else {
            a(i)(j) = max(a(i-1)(j), a(i)(j-1))
          }
        }
      }
      println(a(maxN-1)(maxM-1))
    }
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Longest Common Subsequence

For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \{a,b,c,b,d,a,b\}$ and $Y = \{b,d,c,a,b,a\}$, the sequence $\{b,c,a\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\{b,c,a\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\{b,c,b,a\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\{b,c,b,a\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.

Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.

Input

The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.

Output

For each dataset, print the length of LCS of $X$ and $Y$ in a line.

Constraints

$1 \leq q \leq 150$

$1 \leq$ length of $X$ and $Y$ $\leq 1,000$

$q \leq 20$ if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import scala.io.StdIn.{readInt, readLine};
object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val ig = new IntGraph(n);
        (1 to n).foreach { i =>
            readLine.split(" ").drop(2).map(_.toInt).foreach { j => ig.add(i, j)}
        }
        ig.dSearch.zipWithIndex.drop(1).foreach { e => println("%d %d %d".format(e._2, e._1(0), e._1(1)))}
    }
}
class IntGraph(n: Int) {
    val size: Int = n + 1;
    val matrix: Array[Array[Int]] = Array.ofDim[Int](size, size);
    def add(src: Int, dst: Int): Unit = matrix(src)(dst) = 1;

    def dSearch(): Array[Array[Int]] = {
        val status = Array.ofDim[Int](size, 2);
        def _dSearch(curr: Int, time: Int): Int = {
            status(curr)(0) = time;
            val newTime = 1 + (1 until size).foldLeft(time) { (t, i) =>
                if (matrix(curr)(i) == 1 && status(i)(0) == 0) _dSearch(i, t + 1) else t;
            }
            status(curr)(1) = newTime;
            newTime;
        }
        (1 until size).foreach { i =>
            if (status(i)(0) == 0) {
                _dSearch(i, 1);
            }
        }
        status;
    }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Depth First Search

Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.

This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.

DFS timestamps each vertex as follows:

$d[v]$ records when $v$ is first discovered.

$f[v]$ records when the search finishes examining $v$’s adjacency list.

Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:

$G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.

IDs in the adjacency list are arranged in ascending order.

The program should report the discover time and the finish time for each vertex.

When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.

The timestamp starts with 1.

Input

In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.

Output

For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 100$

Sample Input 1

4
1 1 2
2 1 4
3 0
4 1 3

Sample Output 1

1 1 8
2 2 7
3 4 5
4 3 6

Sample Input 2

6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0

Sample Output 2

1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6

This is example for Sample Input 2 (discover/finish)

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


object Main extends App {
  val n = io.StdIn.readInt()
  val adjacents = Array.fill[Array[Int]](n)(Array())
  for (_ <- 0 until n) {
    val data = io.StdIn.readLine().split(" ").map(_.toInt)
    val id = data(0)-1
    adjacents(id) = data.drop(2).map(_-1)
  }
  val depth = Array.fill[Int](n)(-1)
  def search(x: Int) = {
    val queue = collection.mutable.Queue.empty[Int]
    depth(x) = 0
    queue.enqueue(x)
    loop()
    def loop(): Unit =
      if (queue.isEmpty) ()
      else {
        val i = queue.dequeue()
        for (a <- adjacents(i))
          if (depth(a) < 0) {
            depth(a) = depth(i)+1
            queue.enqueue(a)
          }
        loop()
      }
  }
  search(0)
  for (i <- 0 until n) println(s"${i+1} ${depth(i)}")
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Breadth First Search

Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.

Input

In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.

Constraints

$1 \leq n \leq 100$

Output

For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.

Sample Input 1

4
1 2 2 4
2 1 4
3 0
4 1 3

Sample Output 1

1 0
2 1
3 2
4 1

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import scala.collection.mutable.ArrayBuffer

object Main {

  def main(args: Array[String]): Unit = {

    class UnionSet(par: Array[Int]) {
      def root(x: Int): Int =
        if (par(x) == x) x
        else {
          par(x) = root(par(x))
          par(x)
        }
      def unite(x: Int, y: Int): Unit = {
        val rx = root(x)
        val ry = root(y)
        if (rx != ry)
          par(rx) = ry
      }
      def same(x: Int, y: Int): Boolean =
        root(x) == root(y)
    }
    object UnionSet {
      def apply(n: Int): UnionSet =
        new UnionSet(Array.range(0, n))
    }

    val sc = new java.util.Scanner(System.in)

    val N = sc.nextInt()
    val W = Array.fill(N, N)(sc.nextInt())

    val _E = new ArrayBuffer[(Int, Int)]() // (辺(u,v), 重みw)
    (0 until N) foreach { i =>
      (0 until N) foreach { j =>
        if (W(i)(j) >= 0) {
          _E.append((i, j))
        }
      }
    }
    val E: List[(Int, Int)] = _E.sortBy(e => W(e._1)(e._2)).toList // 辺(軽い順)

    // 最初, 全ての頂点は別の木として初期化する
    val unionset = UnionSet(N)
    var count = 0
    // 軽い辺から見ていき
    E foreach { e =>
      val (u, v) = e
      // u, v が別の木ならば, これは軽い辺なので安全に追加できる.
      if (!unionset.same(u, v)) {
        unionset.unite(u, v)
        count += W(u)(v)
      }
    }

    // 入力が連結グラフであることから,最終的に出来上がった木は1本となり, これが最小全域木である
    // 加えた辺の重さの合計が最小全域木の重さの合計
    println(count)
  }

}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Minimum Spanning Tree

For a given weighted graph $G = (V, E)$, find the minimum spanning tree (MST) of $G$ and print total weight of edges belong to the MST.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, a $n \times n$ adjacency matrix $A$ which represents $G$ is given.
$a_{ij}$ denotes the weight of edge connecting vertex $i$ and vertex $j$. If there is no edge between $i$ and $j$, $a_{ij}$ is given by -1.

Output

Print the total weight of the minimum spanning tree of $G$.

Constraints

$1 \leq n \leq 100$

$0 \leq a_{ij} \leq 2,000$ (if $a_{ij} \neq -1$)

$a_{ij} = a_{ji}$

$G$ is a connected graph

Sample Input 1

5
-1 2 3 1 -1
2 -1 -1 4 -1
3 -1 -1 1 1
1 4 1 -1 3
-1 -1 1 3 -1

Sample Output 1

5

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import scala.io.StdIn.{readInt, readLine};
import scala.annotation.tailrec;
object Main {
    def main(args: Array[String]): Unit = {
        val size = readInt;
        val m = new Array[Array[Int]](size);
        (0 until size).foreach {  i => m(i) = readLine.trim.split(" ").map( a => if (a.toInt == -1) Int.MaxValue else a.toInt)}
        val g = new Graph(size, m);
        val (parent, distance) = g.prim;
        println(distance.sum)
    }
}
case class Graph(size: Int, matrix: Array[Array[Int]]) {
    val INFINITY = Int.MaxValue
    def prim(): (Array[Int], Array[Int]) = {
        // WHITE : 未訪問, GRAY: MST候補ノード, BLACK: MST追加済みノード
        val WHITE = 0; val GRAY = 1; val BLACK = 2;
        val color = new Array[Int](size); // 訪問状態リスト(WHITE, GRAY, BLACK)
        val distance = new Array[Int](size).map( e => INFINITY); //  重みリスト
        val parents = new Array[Int](size); //  親ノードリスト
        @tailrec
        def _prim(curr: Int): Unit = {
            // MSTに属する頂点の集合から最も近いノードの index を取得する
            val idx = (0 until size).foldLeft(-1) { (minidx, i) =>
                if (color(i) != BLACK) {
                    // curr の子ノードをMST候補ノードに追加
                    if (matrix(curr)(i) != -1) {
                        color(i) = GRAY;
                    }
                    if (color(i) == GRAY) {
                        // すでに登録されている重みよりも curr からの重みのほうが小さい場合は
                        // 親ノードと重みを更新する
                        if (matrix(curr)(i) < distance(i)) {
                            distance(i) = matrix(curr)(i);
                            parents(i) = curr;
                        }
                        if (minidx == -1 || distance(i) < distance(minidx)) i else minidx;
                    } else { // color(i) == WHITE
                        // 現時点のMSTに隣接していないノードは評価しない
                        minidx;
                    }
                } else { // color(i) == BLACK
                    // すでにMSTに追加されているノードは評価しない
                    minidx;
                }
            }
            if (idx != -1){
                // MSTから最も距離の近いノードを追加
                color(idx) = BLACK;
                _prim(idx);
            }
        }
        distance(0) = 0;
        parents(0) = -1;
        color(0) = BLACK;
        _prim(0);
        (parents, distance);
    }
}