Any resemblance to any real championship and sport is accidental.The Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship:   the team that kicked most balls in the enemy's goal area wins the game;  the victory gives 3 point to the team, the draw gives 1 point and the defeat gives 0 points;  a group consists of four teams, the teams are ranked by the results of six games: each team plays exactly once with each other team;  the teams that get places 1 and 2 in the group stage results, go to the next stage of the championship. In the group stage the team's place is defined by the total number of scored points: the more points, the higher the place is. If two or more teams have the same number of points, then the following criteria are used (the criteria are listed in the order of falling priority, starting from the most important one):   the difference between the total number of scored goals and the total number of missed goals in the championship: the team with a higher value gets a higher place;  the total number of scored goals in the championship: the team with a higher value gets a higher place;  the lexicographical order of the name of the teams' countries: the country with the lexicographically smaller name gets a higher place. The Berland team plays in the group where the results of 5 out of 6 games are already known. To be exact, there is the last game left. There the Berand national team plays with some other team. The coach asks you to find such score X:Y (where X is the number of goals Berland scored and Y is the number of goals the opponent scored in the game), that fulfills the following conditions:   X > Y, that is, Berland is going to win this game;  after the game Berland gets the 1st or the 2nd place in the group;  if there are multiple variants, you should choose such score X:Y, where value X - Y is minimum;  if it is still impossible to come up with one score, you should choose the score where value Y (the number of goals Berland misses) is minimum.

The input has five lines. Each line describes a game as "team1 team2 goals1:goals2" (without the quotes), what means that team team1 played a game with team team2, besides, team1 scored goals1 goals and team2 scored goals2 goals. The names of teams team1 and team2 are non-empty strings, consisting of uppercase English letters, with length of no more than 20 characters; goals1, goals2 are integers from 0 to 9.  The Berland team is called "BERLAND". It is guaranteed that the Berland team and one more team played exactly 2 games and the the other teams played exactly 3 games.

Print the required score in the last game as X:Y, where X is the number of goals Berland scored and Y is the number of goals the opponent scored. If the Berland team does not get the first or the second place in the group, whatever this game's score is, then print on a single line "IMPOSSIBLE" (without the quotes). Note, that the result score can be very huge, 10:0 for example.

AERLAND DERLAND 2:1
DERLAND CERLAND 0:3
CERLAND AERLAND 0:1
AERLAND BERLAND 2:0
DERLAND BERLAND 4:0

AERLAND DERLAND 2:2
DERLAND CERLAND 2:3
CERLAND AERLAND 1:3
AERLAND BERLAND 2:1
DERLAND BERLAND 4:1

NoteIn the first sample "BERLAND" plays the last game with team "CERLAND". If Berland wins with score 6:0, the results' table looks like that in the end:   AERLAND (points: 9, the difference between scored and missed goals: 4, scored goals: 5)  BERLAND (points: 3, the difference between scored and missed goals: 0, scored goals: 6)  DERLAND (points: 3, the difference between scored and missed goals: 0, scored goals: 5)  CERLAND (points: 3, the difference between scored and missed goals: -4, scored goals: 3) In the second sample teams "AERLAND" and "DERLAND" have already won 7 and 4 points, respectively. The Berland team wins only 3 points, which is not enough to advance to the next championship stage.

import java.util.Scanner

object Main {

	def main(args: Array[String]): Unit = {
		val scanner = new Scanner (System.in)
		for (i <- 1 to 5) read (scanner)
		for (team <- teams.values) {
			val (n, p, d, g, name) = team
			if (n < 3 && name != "BERLAND") enemy = name
		}

		val berland = teams("BERLAND")
		val ans_ix = scores.indexWhere (score => rank (score) <= 2)

		if (ans_ix == -1) {
			println ("IMPOSSIBLE")
		} else {
			val (x, y) = scores(ans_ix)
			println (x + ":" + y)
		}
	}

	val teams = scala.collection.mutable.Map.empty[String, (Int, Int, Int, Int, String)]
	val scores = (List.tabulate (30)(i => List.tabulate (30-i)(j => (i+j+1, j)))).flatten
	var enemy = ""

	def update(team: (Int, Int, Int, Int, String), score: (Int, Int)): (Int, Int, Int, Int, String) = {
		val (n, p, d, g, name) = team
		val (x, y) = score
		val pp = if (x > y) 3 else if (x < y) 0 else 1
		(n + 1, p + pp, d + x - y, g + x, name)
	}

	def read(scanner: Scanner): Unit = {
		val a, b = scanner.next ()
		val xy = scanner.next ()
		val x = xy(0) - '0'
		val y = xy(2) - '0'
		teams(a) = update(teams.getOrElse(a, (0, 0, 0, 0, a)), (x, y))
		teams(b) = update(teams.getOrElse(b, (0, 0, 0, 0, b)), (y, x))
	}

	def compare(a: (Int, Int, Int, Int, String), b: (Int, Int, Int, Int, String)): Int = {
		val (n_a, p_a, d_a, g_a, name_a) = a
		val (n_b, p_b, d_b, g_b, name_b) = b
		if (p_a > p_b) 1
		else if (p_a < p_b) -1
		else if (d_a > d_b) 1
		else if (d_a < d_b) -1
		else if (g_a > g_b) 1
		else if (g_a < g_b) -1
		else if (name_a < name_b) 1
		else if (name_a > name_b) -1
		else 0
	}

	def rank(score: (Int, Int)): Int = {
		val (x, y) = score
		def my_score(): (Int, Int, Int, Int, String) = {
			update(teams("BERLAND"), score)
		}
		def enemy_score(s: (Int, Int, Int, Int, String)): (Int, Int, Int, Int, String) = {
			val (n, p, d, g, name) = s
			if (name == enemy) update(s, (y, x)) else s
		}

		(teams.values.count (x => compare(my_score(), enemy_score(x)) < 0)) + 1
	}

}


Reforms have started in Berland again! At this time, the Parliament is discussing the reform of the calendar. To make the lives of citizens of Berland more varied, it was decided to change the calendar. As more and more people are complaining that "the years fly by...", it was decided that starting from the next year the number of days per year will begin to grow. So the coming year will have exactly a days, the next after coming year will have a + 1 days, the next one will have a + 2 days and so on. This schedule is planned for the coming n years (in the n-th year the length of the year will be equal a + n - 1 day).No one has yet decided what will become of months. An MP Palevny made the following proposal.   The calendar for each month is comfortable to be printed on a square sheet of paper. We are proposed to make the number of days in each month be the square of some integer. The number of days per month should be the same for each month of any year, but may be different for different years.  The number of days in each year must be divisible by the number of days per month in this year. This rule ensures that the number of months in each year is an integer.  The number of days per month for each year must be chosen so as to save the maximum amount of paper to print the calendars. In other words, the number of days per month should be as much as possible. These rules provide an unambiguous method for choosing the number of days in each month for any given year length. For example, according to Palevny's proposition, a year that consists of 108 days will have three months, 36 days each. The year that consists of 99 days will have 11 months, 9 days each, and a year of 365 days will have 365 months, one day each.The proposal provoked heated discussion in the community, the famous mathematician Perelmanov quickly calculated that if the proposal is supported, then in a period of n years, beginning with the year that has a days, the country will spend p sheets of paper to print a set of calendars for these years. Perelmanov's calculations take into account the fact that the set will contain one calendar for each year and each month will be printed on a separate sheet.Repeat Perelmanov's achievement and print the required number p. You are given positive integers a and n. Perelmanov warns you that your program should not work longer than four seconds at the maximum test.

The only input line contains a pair of integers a, n (1 ≤ a, n ≤ 107; a + n - 1 ≤ 107).

Print the required number p.  Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteA note to the first sample test. A year of 25 days will consist of one month containing 25 days. A year of 26 days will consist of 26 months, one day each. A year of 27 days will have three months, 9 days each.

import java.io._

object Solution {
  def main(args: Array[String]) {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val a :: n :: _ = in.readLine.split(" ").map(_.toInt).toList
    val max = a + n
    val d = new Array[Int](max + 1)
    for(i <- 0 to max) {
      d(i) = i
    }
    var i = 2
    while(i * i <= max) {
      if(d(i) == i) {
        var j = i * i
        while(j <= max) {
          if(d(j) == j) {
            d(j) = i
          }
          j += i
        }
      }
      i += 1
    }
    var ans = 0L
    for(i <- a until a + n) {
      var x = i
      var add = x
      while(x != 1) {
        val dd = d(x).toLong * d(x)
        if(x % dd == 0) {
          x /= dd.toInt
          add /= dd.toInt
        }
        else {
          x /= d(x)
        }
      }
      ans += add
    }
    println(ans)
  }
}


Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to print the n-th digit of this string (digits are numbered starting with 1.

The only line of the input contains a single integer n (1 ≤ n ≤ 1000) — the position of the digit you need to print.

NoteIn the first sample the digit at position 3 is '3', as both integers 1 and 2 consist on one digit.In the second sample, the digit at position 11 is '0', it belongs to the integer 10.

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val str = (0 to 1000).mkString
  println(str(n))
}

object A672 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val ret = (1 to 500).flatMap(x => x.toString.toCharArray)
    println(ret(n-1))
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine;
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

/**
  * Created by whimsy on 16/7/11.
  */

object P672A extends App {
    def work() : Int = {
//        val n : Int = StdIn.readInt()
        val n = 3
        var cnt: Int = 0

        for (i <- 1 to n) {
            var t = i
            var ab = ArrayBuffer[Int]()
            while (t > 0) {
                ab += t % 10
                t = t / 10
//                println(t)
            }

            for (j <- 0 to ab.length) {
                println(cnt)
                cnt = cnt + 1
                if (cnt == n) {
                    println(ab(j))
                    return 1
                }
            }
        }
        return 0
    }

    def work2() : Int = {
        val n = StdIn.readInt()

        var content = ""
        var cnt = 0
        while (true) {
            cnt = cnt + 1
            content += cnt

            if (content.length >= n) {
                println(content.charAt(n - 1))
                return 1
            }
        }
        return 0
    }

    work2()
}


Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.Neko has two integers $$$a$$$ and $$$b$$$. His goal is to find a non-negative integer $$$k$$$ such that the least common multiple of $$$a+k$$$ and $$$b+k$$$ is the smallest possible. If there are multiple optimal integers $$$k$$$, he needs to choose the smallest one.Given his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?

The only line contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

Print the smallest non-negative integer $$$k$$$ ($$$k \ge 0$$$) such that the lowest common multiple of $$$a+k$$$ and $$$b+k$$$ is the smallest possible. If there are many possible integers $$$k$$$ giving the same value of the least common multiple, print the smallest one.

NoteIn the first test, one should choose $$$k = 2$$$, as the least common multiple of $$$6 + 2$$$ and $$$10 + 2$$$ is $$$24$$$, which is the smallest least common multiple possible.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val A, B = nl()
    val D = divisors(abs(B - A).toInt)
    var ans = (A * B / gcd(A, B), 0) // (lcm, k)
    REP(D.length) { i =>
      val d = D(i)
      val k = (d - A % d).toInt
      val a = A + k
      val b = B + k
      val lcm = a * b / gcd(a, b)
      if (ans._1 > lcm) {
        ans = (lcm, k)
      }
    }

    out.println(ans._2)
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a
    else gcd(b, a % b)
  }

  def divisors(x: Int): Array[Int] = {
    val pre = ArrayBuffer[Int]()
    val post = ArrayBuffer[Int]()
    REP(math.sqrt(x).toInt, 1) { d =>
      if (x % d == 0) {
        pre += d
        if (d * d != x) post += x / d
      }
    }

    val res = Array.ofDim[Int](pre.length + post.length)
    REP(pre.length)(i => res(i) = pre(i))
    val preLen = pre.length
    val postLen = post.length
    REP(postLen)(i => res(i + preLen) = post(postLen - 1 - i))
    res
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debugDim(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m.length) { i =>
      debug(m(i))
    }
  }

  def debugDimFlip(m: Array[Array[Long]]): Unit = DEBUG {
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.Across all the sets Misha scored a points in total, and Vanya scored b points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible.Note that the game consisted of several complete sets.

The first line contains three space-separated integers k, a and b (1 ≤ k ≤ 109, 0 ≤ a, b ≤ 109, a + b > 0).

If the situation is impossible, print a single number -1. Otherwise, print the maximum possible number of sets.

NoteNote that the rules of the game in this problem differ from the real table tennis game, for example, the rule of "balance" (the winning player has to be at least two points ahead to win a set) has no power within the present problem.

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val Array(k, a, b) = StdIn.readLine().split(" ").map(_.toInt)

  val d = a/k + b /k
  if (d>0 && (a>=k || b>=k) && !(a<k && b%k >0) && !(b<k && a%k>0) ) {
    println(d)
  } else {
    println("-1")
  }
}

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val Array(k, a, b) = StdIn.readLine().split(" ").map(_.toInt)

  val d = (a + b) /k
  if (d>0) {
    println(d)
  } else {
    println("-1")
  }
}

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val Array(k, a, b) = StdIn.readLine().split(" ").map(_.toInt)

  val d = (a + b) /k
  if (d>0 && (a>=k || b>=k) && !(a<k && b%k >0) && !(b<k && a%k>0) ) {
    println(d)
  } else {
    println("-1")
  }
}

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val Array(k, a, b) = StdIn.readLine().split(" ").map(_.toInt)

  val d = (a + b) /k
  if (d>0 && (a>=k || b>=k)) {
    println(d)
  } else {
    println("-1")
  }
}

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val Array(k, a, b) = StdIn.readLine().split(" ").map(_.toInt)

  val d = (a + b) /k
  if (d>0) {
    println("1")
  } else {
    println("-1")
  }
}


The cows have just learned what a primitive root is! Given a prime p, a primitive root  is an integer x (1 ≤ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is. Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime p, help the cows find the number of primitive roots .

The input contains a single line containing an integer p (2 ≤ p < 2000). It is guaranteed that p is a prime.

Output on a single line the number of primitive roots .

NoteThe only primitive root  is 2.The primitive roots  are 2 and 3.

import scala.io._

object Main {

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

		var P = nextInt

		def isPrimitiveRoot(x: Int, P: Int): Boolean = {

			def rec(n: Int, powX: Int): Boolean =
				if (n == P - 1)
					powX == 1
				else
					powX != 1 && rec(n + 1, powX * x % P)

			rec(1, x)
		}

		val roots = (1 until P) filter (isPrimitiveRoot(_, P))

		println(roots.size)
	}

	val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
	var st = new java.util.StringTokenizer("");

	def next() = {
		while (!st.hasMoreTokens())
			st = new java.util.StringTokenizer(in.readLine());
		st.nextToken();
	}

	def nextInt() = java.lang.Integer.parseInt(next());
	def nextDouble() = java.lang.Double.parseDouble(next());
	def nextLong() = java.lang.Long.parseLong(next());
}

import scala.io._
import java.util.StringTokenizer
import java.io.BufferedReader

object Main {

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

        def isPrimitiveRoot(x: Int, p: Int, acc: Int): Boolean =
            if (p == P - 1)
                acc == 1
            else
                acc != 1 &&
                isPrimitiveRoot(x, p + 1, acc * x % P)

        val answer = 1 until P count (x => isPrimitiveRoot(x, 1, x))

        println (answer)
    }

    class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
    {
        private var tokenizer = new StringTokenizer("")
        def readLine() = in.readLine()
        def nextToken(): String = {
            while (!tokenizer.hasMoreTokens) {
                val line = readLine
                if (line == null) return null
                tokenizer = new StringTokenizer(line, splitOn)
            }
            tokenizer.nextToken
        }
        def next[A](f: String => A) = f(nextToken)
        def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())
    }

    implicit val tokenizer = new Tokenizer(Console.in)

    def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
    def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
    def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
    def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
    def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =
        (for (i <- 0 until count) yield f())
}