object Main {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val s = sc.next
    val k = sc.nextLong
    sc.close()

    val ss = matcher(s ++ s)
    val ans = ss.count(_ == '_') * k / 2
    println(ans)
  }

  import scala.collection.mutable
  def matcher(xs: String): mutable.Buffer[Char] = {
    val buf = xs.toBuffer
    (1 until buf.length).foreach(i => {
      if (buf(i - 1) == buf(i)) {
        buf.update(i, '_')
      }
    })
    buf
  }
}


object Main {
  def main(args: Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val s = sc.next.toBuffer
    val k = sc.nextLong
    sc.close()

    var count = 0
    (1 until s.length).foreach(i => {
      if (s(i - 1) == s(i)) {
        s.update(i, '_')
        count += 1
      }
    })
    println(count * k)
  }
}

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

Score : 300 points

Problem Statement

Given is a string S. Let T be the concatenation of K copies of S.
We can repeatedly perform the following operation: choose a character in T and replace it with a different character.
Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different.

Constraints

1 \leq |S| \leq 100

S consists of lowercase English letters.

1 \leq K \leq 10^9

K is an integer.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the minimum number of operations required.

Sample Input 1

issii
2

Sample Output 1

4

T is issiiissii. For example, we can rewrite it into ispiqisyhi, and now any two adjacent characters are different.

Sample Input 2

qq
81

Sample Output 2

81

Sample Input 3

cooooooooonteeeeeeeeeest
999993333

Sample Output 3

8999939997

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.


import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val result = solve(new Scanner(System.in))
    if (result.length > 0) println(result)
  }

  def solve(in: String): String = solve(new Scanner(in))

  def cnt(s: String): Long = {
    var cnt = 0L
    var prev = '.'
    s.foreach { c =>
      if (prev == c) {
        cnt += 1
        prev = '.'
      } else {
        prev = c
      }
    }
    cnt
  }

  def solve(sc: Scanner): String = {
    val S = sc.next
    val K = sc.nextInt

    val c1 = cnt(S)
    val c2 = cnt(S * 2) - c1
    val c3 = cnt(S * 3) - (c1 + c2)
    if (c1 == c3) {
      (((K / 2) * (c1 + c2)) + (K % 2) * c1).toString
    } else {
      (c1 + ((K - 1) * c2)).toString
    }
  }
}


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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))
  }

  @inline private final 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 }
  }
  @inline private final def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  @inline private final def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Workspace {

}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val s1 = ns().toCharArray
    val s2 = s1.clone()
    val k = nl()
    var cntS1, cntS2 = 0
    REP(s1.length - 1) { i =>
      if (s1(i) == s1(i + 1)) {
        s1(i + 1) = '$'
        cntS1 += 1
      }
    }
    cntS2 += 1
    s2(0) = '.'
    REP(s2.length - 1) { i =>
      if (s2(i) == s2(i + 1)) {
        s2(i + 1) = '.'
        cntS2 += 1
      }
    }

    debug(s1.mkString)
    debug(s2.mkString)
    debug(s"cntS1:$cntS1 cntS2:$cntS2")

    var ans = 1e18.toLong
    if (s1.last != s2.head && s2.last != s1.head) {
      debug("1212 or 2121")
      ans = min(ans, cntS1 * ((k + 1) / 2) + cntS2 * (k / 2))
      ans = min(ans, cntS1 * (k / 2) + cntS2 * ((k + 1) / 2))
    }
    if (s1.last != s2.head && s2.last != s2.head) {
      debug("1222")
      ans = min(ans, cntS1 + (k - 1) * cntS2)
    }
    if (s1.last != s1.head) {
      debug("1111")
      ans = min(ans, cntS1 * k)
    }
    if (s2.last != s2.head) {
      debug("2222")
      ans = min(ans, cntS2 * k)
    }
    if (s2.last != s1.head && s1.last != s1.head) {
      debug("2111")
      ans = min(ans, cntS2 + (k - 1) * cntS1)
    }

    out.println(ans)
  }
}


import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val result = solve(new Scanner(System.in))
    if (result.length > 0) println(result)
  }

  def solve(in: String): String = solve(new Scanner(in))

  def cnt(s: String): Long = {
    var cnt = 0L
    var prev = '.'
    s.foreach { c =>
      if (prev == c) {
        cnt += 1
        prev = '.'
      } else {
        prev = c
      }
    }
    cnt
  }

  def solve(sc: Scanner): String = {
    val S = sc.next
    val K = sc.nextInt

    val c1 = cnt(S)
    val c2 = cnt(S + S)

    ((K / 2) * c2 + (K % 2) * c1).toString
  }
}


import scala.io.StdIn._
import scala.collection.mutable.PriorityQueue

object Main {
  def main(args: Array[String]) = {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val q = PriorityQueue[Long]() ++ readLine().split(" ").map(_.toLong)
    for(_ <- 0 until m) {
      q.enqueue(q.dequeue()/2)
    }
    println(q.sum)
  }
}

Score : 400 points

Problem Statement

Takahashi is going to buy N items one by one.

The price of the i-th item he buys is A_i yen (the currency of Japan).

He has M discount tickets, and he can use any number of them when buying an item.

If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen.

What is the minimum amount of money required to buy all the items?

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the minimum amount of money required to buy all the items.

Sample Input 1

3 3
2 13 8

Sample Output 1

9

We can buy all the items for 9 yen, as follows:

Buy the 1-st item for 2 yen without tickets.

Buy the 2-nd item for 3 yen with 2 tickets.

Buy the 3-rd item for 4 yen with 1 ticket.

Sample Input 2

4 4
1 9 3 5

Sample Output 2

6

Sample Input 3

1 100000
1000000000

Sample Output 3

0

We can buy the item priced 1000000000 yen for 0 yen with 100000 tickets.

Sample Input 4

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

9500000000


object Main {
  def main(args: Array[String]): Unit = {
    solve
  }

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    var m = sc.nextInt
    val pq = collection.mutable.PriorityQueue[Long]()
    for (i <- 0 until n) {
      pq.enqueue(sc.nextLong())
    }

    // 最後に合計出せばいいのか
    //    var sum = pq.toList.sum
    while (m > 0) {
      val max = pq.dequeue()
      val half = max / 2
      //      sum -= max - tmp
      pq.enqueue(half)
      m -= 1
    }

    println(pq.toList.sum)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val factors = scala.io.StdIn.readLine.split(" ").map{_.toInt}
    var prices  = scala.io.StdIn.readLine.split(" ").map{_.toLong}.sorted

    var count = 1
    while(count <= factors(1).toInt) {
      prices(prices.length - 1) = (prices.last/2)
      prices = prices.sorted
      count += 1
    }

    var sum = 0l
    prices.foreach{ i =>
      sum += i
    }
    println(sum)
  }
}


//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.collection.mutable
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 queue = new mutable.PriorityQueue[(Long, (Int, Int))]()
    val N, M = sc.nextInt()
    val A = Array.fill(N)(sc.nextLong())
    A.zipWithIndex.foreach {
      case (num, index) => {
        queue.enqueue((num, (index, 0)))
      }
    }
    (0 until M).foreach(_ => {
      val now = queue.dequeue()
      val index = now._2._1
      val num = now._2._2 + 1
      queue.enqueue((A(index) / (1L << num), (index, num)))
    })
    println(queue.foldLeft(0L) { case (x, y) => x + y._1 })
  }

  @scala.annotation.tailrec
  def recursive(now: ((Long, Long), (Long, Long), (Long, Long)), n: Int, sc: => Scanner): ((Long, Long), (Long, Long), (Long, Long)) = {
    if (n == 0) now else {
      val move = ((sc.nextLong(), sc.nextLong()), (sc.nextLong(), sc.nextLong()))
      if (now._1 == move._1) {
        recursive((move._2, now._2, now._3), n - 1, sc)
      } else if (now._2 == move._1) {
        recursive((now._1, move._2, now._3), n - 1, sc)
      } else if (now._3 == move._1) {
        recursive((now._1, now._2, move._2), n - 1, sc)
      } else {
        recursive((now._1, now._2, now._3), n - 1, sc)
      }
    }
  }

  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]()

  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 =>

      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
    }
    } =>

      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())
  }
}


object Main extends App {

  val inputnm = scala.io.StdIn.readLine()
  val nmArray = inputnm.split(" ").map(_.toInt).toVector
  val inputa = scala.io.StdIn.readLine()

  val n = nmArray(0)
  val m = nmArray(1)
  var aArray = inputa.split(" ").map(_.toLong).toVector

  (1 to m).foreach { _ =>
    if (aArray.size > 0) {
      val max = aArray.max
      aArray = aArray.updated(aArray.indexWhere(_ == max), max / 2L).filter(_ > 0)
    }
  }

  println(aArray.sum)

}


import scala.io.StdIn
import scala.math._
object Main extends App {
  val List(n,m) = StdIn.readLine().split(" ").map(_.toInt).toList
  var a = StdIn.readLine().split(" ").map(_.toLong).sorted.reverse
  for (i <- 1 to m) {
    a(0) = ceil(a(0) / 2).toLong
    a = a.sorted(Ordering[Long].reverse)
  }
  println(a.sum)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt() // 最初の数字を読み取る
  val m = sc.nextInt()
  var list = Array.fill(n)(sc.nextLong()) // nextIntがn回呼ばれる
  val num = list.length - 1

  list = list.sorted.reverse

  Range(0, m).foreach { _ =>
    val max = list.indexOf(list.max)
    list(max) = list(max)/2
  }

  print(list.sum)
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N, M = in.next().toInt
  val A = new Array[Long](N+1)
  for (i <- 1 to N)
    A(i) = in.next().toLong

  ///
  def check(n: Long): Boolean = {
    var rest = M
    var flag = true
    breakable {
      for (i <- 1 to N) {
        var div = 1L
        while (A(i) >= (n+1) * div) {
          rest -= 1
          div *= 2L
        }

        if (rest < 0){
          flag = false
          break
        }
      }
    }

    flag
  }

  // 条件を満たす最小の値を返す
  def binarySearch(min: Long, max: Long): Long = {
    val mid: Long = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(min) match{
          case true  => min
          case false => max
        }
      case _ =>
        (check(mid)) match{
          case true  => binarySearch(min, mid)
          case false => binarySearch(mid, max)
        }
    }
  }

  /** */
  val base = binarySearch(0L, 1e9.toLong)

  var ans = 0L
  var rest = M
  for (i <- 1 to N) {
    var div = 1L
    while (A(i) >= (base+1) * div) {
      rest -= 1
      div *= 2L
    }

    A(i) = A(i) / div
  }

  val B = A.sorted

  breakable {
    for (i <- (1 to N).reverse) {
      if (rest == 0)
        break
      else {
        rest -= 1
        B(i) = B(i) / 2
      }
    }
  }
  ans = B.sum
  println(ans)

}

class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import collection.mutable.PriorityQueue
import scala.util.control.Breaks._

object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val s = sc.next
    var rw = new Array[Int](0) :+ 0
    var sum = 0
    val a = 'a'.toInt
    s.foreach { v =>
      sum += (v.toInt - a)
      rw = rw :+ sum
    }
    //println(rw.deep)
    for(len <- (s.length)/2 to (1, -1)) {
      for(i <- 0 to s.length-len) {
        for(j <- i+len to s.length-len) {
          if (rw(i+len)-rw(i) == rw(j+len)-rw(j)) {
            //println(s.substring(i, i+len))
            //println(s.substring(j, j+len))
            breakable {
              for(x <- 0 to len-1) {
                if (s(i+x) != s(j+x)) break
              }
              println(len)
              System.exit(0)
            }
          }
        }
      }
    }
    println(0)
  }
}

Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

2 \leq N \leq 5 \times 10^3

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5


import collection.mutable.PriorityQueue

object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val s = sc.next
    var rw = new Array[Int](0) :+ 0
    var sum = 0
    val a = 'a'.toInt
    s.foreach { v =>
      sum += (v.toInt - a)
      rw = rw :+ sum
    }
    //println(rw.deep)
    for(len <- (s.length-1)/2 to (1, -1)) {
      for(i <- 0 to s.length-len) {
        for(j <- i+len to s.length-len) {
          if (rw(i+len)-rw(i) == rw(j+len)-rw(j)) {
            //println(s.substring(i, i+len))
            //println(s.substring(j, j+len))
            if (s.substring(i, i+len) == s.substring(j, j+len)) {
              println(len)
              System.exit(0)
            }
          }
        }
      }
    }
    println(0)
  }
}


//object ABC141EJvm {
object Main {

  def main(args: Array[String]): Unit = println(solve(parse()))

  def solve(input: (Int, String)): Int = {
    val (n, s) = input
    val maxSubStringLength = s.length / 2 - (if (s.length % 2 == 0) 1 else 0)
    val r = (1 to maxSubStringLength).reverse.find { i =>
      (0 until i).exists { j =>
        val slicedString = s.slice(j, j + i)
        (s.take(j) ++ s.drop(j + i)).contains(slicedString)
      }
    }.toList
    if (r.isEmpty) 0 else r.max
  }

  def parse(): (Int, String) = {
    val input: List[String] = io.Source.stdin.getLines().toList
    val n :: s :: Nil = input
    (n.toInt, s)
  }
}


//object ABC141EJvm {
object Main {

  def main(args: Array[Int]): Unit = println(solve(parse()))

  def solve(input: (Int, Int, List[Int])): Int = {
    val (n, m, an) = input
    val maxSubStringLength = an.length / 2 - (if (an.length % 2 == 0) 1 else 0)
    val r = (1 to maxSubStringLength).reverse.find { i =>
      (0 until i).exists { j =>
        val slicedString = an.slice(j, j + i)
        (an.take(j) ++ an.drop(j + i)).contains(slicedString)
      }
    }.toList
    if (r.isEmpty) 0 else r.max
  }

  def parse(): (Int, Int, List[Int]) = {
    val input: List[List[Int]] = io.Source.stdin.getLines().map(_.map(_.toInt).toList).toList
    val n :: k :: Nil = input.head
    val _ :: an :: Nil = input
    (n, k, an)
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  private[this] val S = "0" + in.next()

  //
  // a は bに含まれているか
  def contain(a: String, b: String): Boolean = {
    val B = 5570293
    val h = 1e9.toLong

    val al = a.length; val bl = b.length
    if (al > bl)
      return false

    // B の al 乗を計算
    var t = 1L
    for (_ <- 1 to al) {
      t *= B
      t %= h
    }

    // aとbの最初のal文字に関するハッシュ値を計算
    var ah = 0L; var bh = 0L
    for (i <- 0 until al)
      ah = (ah * B + a(i).toLong) % h
    for (i <- 0 until al)
      bh = (bh * B + b(i).toLong) % h

    // bの場所を1つずつ進めながらハッシュ値をチェック
    for (i <- 0 to bl-al) {
      if (ah == bh)
        return true
      if (i + al < bl) {
        bh *= B
        bh %= h
        bh += b(i+al).toLong - b(i).toLong * t
        if(bh < 0)
          bh += h * 1000
        bh %= h
      }
    }

    false
  }

  private[this] def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    contain(a, b)
  }

  // 条件を満たす最大の値を返す
  private[this] def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  private[this] var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  private[this] val S = "0" + in.next()

  //
  // a は bに含まれているか
  def contain(a: String, b: String): Boolean = {
    val B = 5570293
    val h = 1e9.toLong

    val al = a.length; val bl = b.length
    if (al > bl)
      return false

    // B の al 乗を計算
    var t = 1L
    for (_ <- 1 to al) {
      t *= B
      t %= h
    }

    // aとbの最初のal文字に関するハッシュ値を計算
    var ah = 0L; var bh = 0L
    for (i <- 0 until al)
      ah = (ah * B + a(i).toLong) % h
    for (i <- 0 until al)
      bh = (bh * B + b(i).toLong) % h

    // bの場所を1つずつ進めながらハッシュ値をチェック
    for (i <- 0 to bl-al) {
      if (ah == bh && a == b.substring(i, i+al))
        return true
      if (i + al < bl) {
        bh *= B
        bh %= h
        bh += b(i+al).toLong - b(i).toLong * t
        if(bh < 0)
          bh += h * 100
        bh %= h
      }
    }

    false
  }

  private[this] def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    contain(a, b)
  }

  // 条件を満たす最大の値を返す
  private[this] def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  private[this] var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  private[this] val S = "0" + in.next()

  //
  // a は bに含まれているか
  def contain(a: String, b: String): Boolean = {
    val B = 5570293
    val h = 2<<32

    val al = a.length; val bl = b.length
    if (al > bl)
      return false

    // B の al 乗を計算
    var t = 1L
    for (_ <- 1 to al) {
      t *= B
      t %= h
    }

    // aとbの最初のal文字に関するハッシュ値を計算
    var ah = 0L; var bh = 0L
    for (i <- 0 until al)
      ah = (ah * B + a(i).toLong) % h
    for (i <- 0 until al)
      bh = (bh * B + b(i).toLong) % h

    // bの場所を1つずつ進めながらハッシュ値をチェック
    for (i <- 0 to bl-al) {
      if (ah == bh && a == b.substring(i, i+al))
        return true
      if (i + al < bl) {
        bh *= B
        bh %= h
        bh += b(i+al).toLong - b(i).toLong * t
        if(bh < 0)
          bh += h
        bh %= h
      }
    }

    false
  }

  private[this] def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    contain(a, b)
  }

  // 条件を満たす最大の値を返す
  private[this] def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  private[this] var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  private[this] val S = "0" + in.next()

  //
  // a は bに含まれているか
  def contain(a: String, b: String): Boolean = {
    val B = 5570293
    val B2 = 5573333
    val h = 2<<32

    val al = a.length; val bl = b.length
    if (al > bl)
      return false

    // B の al 乗を計算
    var t = 1L; var t2 = 1L
    for (_ <- 1 to al) {
      t *= B
      t %= h

      t2 *= B2
      t %= h
    }

    // aとbの最初のal文字に関するハッシュ値を計算
    var ah = 0L; var bh = 0L
    var ah2 = 0L; var bh2 = 0L
    for (i <- 0 until al) {
      ah = (ah * B + a(i).toLong) % h
      ah2 = (ah2 * B2 + a(i).toLong) % h
    }
    for (i <- 0 until al) {
      bh = (bh * B + b(i).toLong) % h
      bh2 = (bh2 * B2 + b(i).toLong) % h
    }

    // bの場所を1つずつ進めながらハッシュ値をチェック
    for (i <- 0 to bl-al) {
      if (ah == bh && ah2 == bh2)
        return true
      if (i + al < bl) {
        bh *= B
        bh %= h
        bh += b(i+al).toLong - b(i).toLong * t
        if(bh < 0)
          bh += h
        bh %= h

        bh2 *= B2
        bh2 %= h
        bh2 += b(i+al).toLong - b(i).toLong * t
        if(bh2 < 0)
          bh2 += h
        bh2 %= h

      }
    }

    false
  }

  private[this] def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    contain(a, b)
  }

  // 条件を満たす最大の値を返す
  private[this] def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  private[this] var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  private[this] val S = "0" + in.next()

  //
  // a は bに含まれているか
  def contain(a: String, b: String): Boolean = {
    val B = 5570293
    val h = 2<<32

    val al = a.length; val bl = b.length
    if (al > bl)
      return false

    // B の al 乗を計算
    var t = 1L
    for (_ <- 1 to al) {
      t *= B
      t %= h
    }

    // aとbの最初のal文字に関するハッシュ値を計算
    var ah = 0L; var bh = 0L
    for (i <- 0 until al)
      ah = (ah * B + a(i).toLong) % h
    for (i <- 0 until al)
      bh = (bh * B + b(i).toLong) % h

    // bの場所を1つずつ進めながらハッシュ値をチェック
    for (i <- 0 to bl-al) {
      if (ah == bh)
        return true
      if (i + al < bl) {
        bh *= B
        bh %= h
        bh += b(i+al).toLong - b(i).toLong * t
        if(bh < 0)
          bh += h
        bh %= h
      }
    }

    false
  }

  private[this] def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    contain(a, b)
  }

  // 条件を満たす最大の値を返す
  private[this] def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  private[this] var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  private[this] val S = "0" + in.next()

  //
  // a は bに含まれているか
  def contain(a: String, b: String): Boolean = {
    val B = 1e9.toLong + 7
    val h = 1e9.toLong + 9

    val al = a.length; val bl = b.length
    if (al > bl)
      return false

    // B の al 乗を計算
    var t = 1L
    for (_ <- 1 to al) {
      t *= B
      t %= h
    }

    // aとbの最初のal文字に関するハッシュ値を計算
    var ah = 0L; var bh = 0L
    for (i <- 0 until al)
      ah = (ah * B + a(i).toLong) % h
    for (i <- 0 until al)
      bh = (bh * B + b(i).toLong) % h

    // bの場所を1つずつ進めながらハッシュ値をチェック
    for (i <- 0 to bl-al) {
      if (ah == bh)
        return true
      if (i + al < bl) {
        bh *= B
        bh %= h
        bh += b(i+al).toLong - b(i).toLong * t
        bh += h * 200
        bh %= h
      }
    }

    false
  }

  private[this] def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    contain(a, b)
  }

  // 条件を満たす最大の値を返す
  private[this] def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  private[this] var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import scala.collection.mutable
import scala.io.StdIn
import java.util._
import util.control.Breaks._

object Main extends App {
  StdIn.readLine()
  val l = StdIn.readLine()
  var max = 0
  for (c <- 0 until l.size){
    for(i <- 1 until l.size-c){
      if (l(c+i) == l(c)){
        breakable {
         // println(c,i)
          if (Math.min(i, l.size-c-i) > max) {
            for (j <- 0 until Math.min(i, l.size - c - i)) {
              //println(l(c + i + j), l(c + j))
              if (l(c + i + j) == l(c + j)) {
                if (j + 1 > max) max = j + 1
              } else break
            }
          }
        }
      }
    }
  }
  println(max)
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  private[this] val S = "0" + in.next()

  //
  private[this] def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    b.contains(a)
  }

  // 条件を満たす最大の値を返す
  private[this] def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  private[this] var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Queue, PriorityQueue}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  val S = "0" + in.next()

  //
  def check(end: Int, begin: Int): Boolean = {
    val a = S.substring(begin, end+1)
    val b = S.substring(end+1, N+1)

    b.contains(a)
  }

  // 条件を満たす最大の値を返す
  def binarySearch(min: Int, max: Int, begin: Int): Int = {
    val mid: Int = (max + min) / 2
      (max - min) match{
      case 0 | 1 =>
        check(max, begin) match{
          case true  => max
          case false => min
        }
      case _ =>
        (check(mid, begin)) match{
          case true  => binarySearch(mid, max, begin)
          case false => binarySearch(min, mid, begin)
        }
    }
  }

  var ans = 0
  for (i <- 1 to N-1) {
    if (check(i, i)) {
      val tmp = binarySearch(i, i + (N-i) / 2, i) - (i-1)
      ans = Math.max(ans, tmp)
    }
  }
  println(ans)
}

class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val a = sc.nextInt
  val s = sc.next
  println(if (a < 3200) "red" else s)
}

Score : 100 points

Problem Statement

You will be given an integer a and a string s consisting of lowercase English letters as input.

Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

Constraints

2800 \leq a < 5000

s is a string of length between 1 and 10 (inclusive).

Each character of s is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

a
s

Output

If a is not less than 3200, print s; if a is less than 3200, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

a = 3200 is not less than 3200, so we print s = pink.

Sample Input 2

3199
pink

Sample Output 2

red

a = 3199 is less than 3200, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

a = 4049 is not less than 3200, so we print s = red.


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val a = sc.nextInt
  val s = sc.next
  println(if (a < 3200) a else s)
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val a = sc.nextInt()
  println(if (a >= 3200) sc.next() else "red")
}


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)

  val a = sc.nextInt
  val s = sc.next

  val res = if(a >= 3200) s else "red"

  println(res)

}


import java.util.Scanner

object Main {

  def read(): (Int, String) = {
    val sc: Scanner = new Scanner(System.in)
    val a = sc.nextInt
    val s = sc.next
    sc.close()
    (a, s)
  }

  def solve(a: Int, s: String): String = {
    if(a < 3200) "red" else s
  }

  def main(args: Array[String]): Unit = {
    val (a, s) = read()
    println(solve(a, s))
  }

}


object Main {
  def main(args: Array[String]) {
    val input = io.Source.stdin.getLines().mkString("\n");
    println(solve(input))

    def solve(input: String): String = {
      val a :: s :: _ = input.split("\n").toList
      if (a.toInt >= 3200) {
        s
      } else {
        "red"
      }
    }
  }
}


object Main {
  def main(args: Array[String]) {
    if (sys.env.getOrElse("TEST", "") == "1") {
      println(test());
    } else {
      val input = io.Source.stdin.getLines().mkString("\n");
      println(solve(input).trim());
    }
  }

  def solve(input: String): String = {
    val a :: s :: _ = input.split("\n").toSeq
    if (a.toInt >= 3200) {
      s
    } else {
      "red"
    }
  }

  val tests = List(
    """3200
      |pink""".stripMargin -> """pink""".stripMargin,
    """3199
      |pink""".stripMargin -> """red""",
    """4049
      |red""".stripMargin -> """red"""
  );

  def test(): String = {
    tests
      .map { case (i, o) => (i.trim(), o.trim()) }
      .zipWithIndex
      .map {
        case ((input, outputExpect), i) => {
          val output = solve(input).trim();
          s"test${i + 1}:" + (if (output == outputExpect) {
                                "Passed"
                              } else {
                                s"Failed\nexpect:\n${outputExpect}\noutput:\n${output}"
                              })
        }
      }
      .mkString("\n");
  }
}


import scala.io.StdIn._

object Main extends App {
  val a = readInt()
  val s = readLine()

  if (a >= 3200) println(s) else println("red")
}


object Main extends App {
  val a = io.StdIn.readInt()
  val s = io.StdIn.readLine()
  if( a < 3200 ) {
  	println("red")
  } else {
  	println(s)
  }
}


object Main extends App {
  val a = scala.io.StdIn.readInt()
  val s =  scala.io.StdIn.readLine()
  println(
    if (a >= 3200)
      s
    else
      "red"
  )
}


object Main{
  def main(args: Array[String]) = {
    val arr1 = io.StdIn.readLine().toInt
    val arr2 = io.StdIn.readLine()
    val a = arr1
    val s = arr2(0).toString
    if(a >= 3200) println(s) else println("red")
  }
}


object Main extends App {
  val a = scala.io.StdIn.readLine.toInt
  val s = scala.io.StdIn.readLine
  if(a >=3200) {
    println(s)
  } else {
    println("red")

  }

}


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }

  case class Edge(a: Int, b: Int, c: Long)
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val a = ni()
    val s = ns()
    if (a >= 3200) out.println(s)
    else out.println("red")
  }
}


object Main extends App {
  print(if(readInt<3200){
    "red"}else{readLine})
}


object Main {

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

    val a = sc.nextInt(); sc.nextLine()
    val s = sc.nextLine()
    if (a >= 3200) println(s) else println("red")
  }

}


object Main extends App {
  val sc = new java.util.Scanner(System.in);
  val n, q = sc.nextInt();
  val abs = Array.fill(n - 1)((sc.nextInt() - 1, sc.nextInt() - 1));
  val pxs = Array.fill(q)((sc.nextInt() - 1, sc.nextInt()));

  val abs2 = Array.fill[List[Int]](n)(Nil);
  abs.foreach { case (a, b) =>
    abs2(a) = b :: abs2(a);
    abs2(b) = a :: abs2(b);
  }

  val answer = Array.fill(n)(0);
  pxs.foreach { case (p, x) =>
    answer(p) += x;
  }
  @scala.annotation.tailrec
  def sub(stack: List[(Int, List[Int])]): Unit = {
    stack match {
      case Nil => ;
      case (_, Nil) :: stack2 => sub(stack2);
      case (parent, h :: tail) :: stack2 =>
        val cs = abs2(h).filter(_ != parent);
        if (!cs.isEmpty) {
          cs.foreach { c =>
            answer(c) += answer(h);
          }
          sub((h, cs) :: (parent, tail) :: stack2);
        } else if (!tail.isEmpty) {
          sub((parent, tail) :: stack2);
        } else {
          sub(stack2);
        }
    }
  }
  sub((-1, List(0)) :: Nil);

  println(answer.mkString(" "));
}

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq Q \leq 2 \times 10^5

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10

Sample Output 2

20 20 20 20 20 20


import scala.io.StdIn

case class Node(n: Int, var reached: Boolean = false, var x: Int = 0, var subs: List[Node] = List()) {
  def addSub(sub: Node): Unit = this.subs +:= sub

  def trace(acc: Long, additions: Array[Int], result: Array[Long]): Array[Long] = {
    reached = true
    val _acc = acc + additions(n).toLong
    result(n) = _acc
    subs.filterNot(_.reached).foreach(_.trace(_acc, additions, result))
    result
  }

  override def toString: String = s"{ $n | +$x | (${subs.mkString(", ")}) }"
}

object Main extends App {
  val Array(n, q) = StdIn.readLine.split(" ").map(_.toInt)
  val abs = fromStdIn(n - 1)
  val pxs = fromStdIn(q)

  val nodes: Array[Node] = Array.ofDim(n + 1)
  abs.foreach { case (a, b) =>
    val na = if (nodes(a) != null) nodes(a) else Node(a)
    val nb = if (nodes(b) != null) nodes(b) else Node(b)
    na.addSub(nb)
    nb.addSub(na)
    nodes(a) = na
    nodes(b) = nb
  }

//  nodes.tail.foreach(
//    node => println(s"${node.n}: ${node.subs.map(_.n)}")
//  )

  val additions = Array.ofDim[Int](n + 1)
  for ((p, x) <- pxs) {
    additions(p) += x
  }

  val result = Array.ofDim[Long](n + 1)
  nodes(1).trace(0L, additions, result)

  println(result.tail.mkString(" "))

  def fromStdIn(n: Int): Seq[(Int, Int)] =
    for (_ <- 1 to n)
      yield {
        val line = StdIn.readLine.split(" ").map(_.toInt)
        (line(0), line(1))
      }
}


import scala.io.StdIn

case class Node(n: Int, var x: Int = 0, var subs: List[Node] = List()) {
  def addSub(sub: Node): Unit = this.subs +:= sub

  def trace(acc: Long, additions: Array[Int], result: Array[Long]): Array[Long] = {
    val _acc = acc + additions(n).toLong
    result(n) = _acc
    subs.foreach(_.trace(_acc, additions, result))
    result
  }

  override def toString: String = s"{ $n | +$x | (${subs.mkString(", ")}) }"
}

object Main extends App {
  val Array(n, q) = StdIn.readLine.split(" ").map(_.toInt)
  val abs = fromStdIn(n - 1)
  val pxs = fromStdIn(q)

  val nodes: Array[Node] = Array.ofDim(n + 1)
  nodes(1) = Node(1)
  abs.foreach { case (a, b) =>
    if (nodes(a) != null && nodes(b) == null) {
      val node = Node(b)
      nodes(a).addSub(node)
      nodes(b) = node

    } else if (nodes(a) == null && nodes(b) != null) {
      val node = Node(a)
      nodes(b).addSub(Node(a))
      nodes(a) = node
    } else if (nodes(a) == null && nodes(b) == null) {
      nodes(a) = Node(a)
      nodes(b) = Node(b)
    } else if (nodes(a) != null && nodes(b) != null) {

    } else {
      1 / 0
    }
  }

  val additions = Array.ofDim[Int](n + 1)
  for ((p, x) <- pxs) {
    additions(p) += x
  }

  val result = Array.ofDim[Long](n + 1)
  nodes(1).trace(0L, additions, result)

  println(result.tail.mkString(" "))

  def fromStdIn(n: Int): Seq[(Int, Int)] =
    for (_ <- 1 to n)
      yield {
        val line = StdIn.readLine.split(" ").map(_.toInt)
        (line(0), line(1))
      }
}


import scala.io.StdIn

case class Node(n: Int, var x: Int = 0, var subs: List[Node] = List()) {
  def addSub(sub: Node): Unit = this.subs +:= sub

  def trace(acc: Long, additions: Array[Int], result: Array[Long]): Array[Long] = {
    val _acc = acc + additions(n).toLong
    result(n) = _acc
    subs.foreach(_.trace(_acc, additions, result))
    result
  }

  override def toString: String = s"{ $n | +$x | (${subs.mkString(", ")}) }"
}

object Main extends App {
  val Array(n, q) = StdIn.readLine.split(" ").map(_.toInt)
  val abs = fromStdIn(n - 1)
  val pxs = fromStdIn(q)

  val nodes: Array[Node] = Array.ofDim(n + 1)
  nodes(1) = Node(1)
  abs.foreach { case (a, b) =>
    if (nodes(a) != null && nodes(b) == null) {
      val node = Node(b)
      nodes(a).addSub(node)
      nodes(b) = node

    } else if (nodes(a) == null && nodes(b) != null) {
      val node = Node(a)
      nodes(b).addSub(Node(a))
      nodes(a) = node
    } else if (nodes(a) == null && nodes(b) == null) {
      nodes(a) = Node(a)
      nodes(b) = Node(b)
    } else {
//      1 / 0
    }
  }

  val additions = Array.ofDim[Int](n + 1)
  for ((p, x) <- pxs) {
    additions(p) += x
  }

  val result = Array.ofDim[Long](n + 1)
  nodes(1).trace(0L, additions, result)

  println(result.tail.mkString(" "))

  def fromStdIn(n: Int): Seq[(Int, Int)] =
    for (_ <- 1 to n)
      yield {
        val line = StdIn.readLine.split(" ").map(_.toInt)
        (line(0), line(1))
      }
}


import scala.io.StdIn

case class Node(n: Int, var x: Int = 0, var subs: List[Node] = List()) {
  def addSub(sub: Node): Unit = this.subs +:= sub

  def trace(acc: Long, additions: Array[Int], result: Array[Long]): Array[Long] = {
    val _acc = acc + additions(n).toLong
    result(n) = _acc
    subs.foreach(_.trace(_acc, additions, result))
    result
  }

  override def toString: String = s"{ $n | +$x | (${subs.mkString(", ")}) }"
}

object Main extends App {
  val Array(n, q) = StdIn.readLine.split(" ").map(_.toInt)
  val abs = fromStdIn(n - 1)
  val pxs = fromStdIn(q)

  val nodes: Array[Node] = Array.ofDim(n + 1)
  nodes(1) = Node(1)
  abs.foreach { case (a, b) =>
    if (nodes(a) != null && nodes(b) == null) {
      val node = Node(b)
      nodes(a).addSub(node)
      nodes(b) = node

    } else if (nodes(a) == null && nodes(b) != null) {
      val node = Node(a)
      nodes(b).addSub(Node(a))
      nodes(a) = node
    } else {
      1 / 0
    }
  }

  val additions = Array.ofDim[Int](n + 1)
  for ((p, x) <- pxs) {
    additions(p) += x
  }

  val result = Array.ofDim[Long](n + 1)
  nodes(1).trace(0L, additions, result)

  println(result.tail.mkString(" "))

  def fromStdIn(n: Int): Seq[(Int, Int)] =
    for (_ <- 1 to n)
      yield {
        val line = StdIn.readLine.split(" ").map(_.toInt)
        (line(0), line(1))
      }
}


import scala.io.StdIn

case class Node(n: Int, var x: Int = 0, var subs: List[Node] = List()) {
  def addSub(sub: Node): Unit = this.subs +:= sub

  def trace(acc: Long, additions: Array[Int], result: Array[Long]): Array[Long] = {
    val _acc = acc + additions(n).toLong
    result(n) = _acc
    subs.foreach(_.trace(_acc, additions, result))
    result
  }

  override def toString: String = s"{ $n | +$x | (${subs.mkString(", ")}) }"
}

object Main extends App {
  val Array(n, q) = StdIn.readLine.split(" ").map(_.toInt)
  val abs = fromStdIn(n - 1)
  val pxs = fromStdIn(q)

  val nodes: Array[Node] = Array.ofDim(n + 1)
  nodes(1) = Node(1)
  abs.foreach { case (a, b) =>
    if (nodes(a) != null && nodes(b) == null) {
      val node = Node(b)
      nodes(a).addSub(node)
      nodes(b) = node

    } else if (nodes(a) == null && nodes(b) != null) {
      val node = Node(a)
      nodes(b).addSub(Node(a))
      nodes(a) = node
    }
  }

  val additions = Array.ofDim[Int](n + 1)
  for ((p, x) <- pxs) {
    additions(p) += x
  }

  val result = Array.ofDim[Long](n + 1)
  nodes(1).trace(0L, additions, result)

  println(result.tail.mkString(" "))

  def fromStdIn(n: Int): Seq[(Int, Int)] =
    for (_ <- 1 to n)
      yield {
        val line = StdIn.readLine.split(" ").map(_.toInt)
        (line(0), line(1))
      }
}


import scala.io.StdIn

object Main extends App {
  val Array(n, q) = StdIn.readLine.split(" ").map(_.toInt)
  val abs = fromStdIn(n - 1)
  val pxs = fromStdIn(q)

  val subsArray = Array.fill[Seq[Int]](n + 1)(Seq())
  abs.groupBy(_._1).foreach {
    case (i, subs) => subsArray(i) = subs.map(_._2)
  }

  val addsArray = Array.fill[Int](n + 1)(0)
  for ((p, x) <- pxs) {
    addsArray(p) += x
  }

  val result = Array.fill[Long](n + 1)(0L)

  def rec(n: Int, acc: Long): Unit = {
    val _acc = acc + addsArray(n).toLong
    result(n) = _acc
    subsArray(n).foreach(sub => rec(sub, _acc))
  }

  rec(1, 0L)

  println(
    result.tail.mkString(" ")
  )

  def fromStdIn(n: Int): Seq[(Int, Int)] =
    for (_ <- 1 to n)
      yield {
        val line = StdIn.readLine.split(" ").map(_.toInt)
        (line(0), line(1))
      }
}


import scala.collection.immutable.Queue
import scala.collection.mutable.ArrayBuffer

object Main {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val N, Q = sc.nextInt()

    // 操作jのたびに, その頂点自体にカウントを足しておいて, 最後に頂点から辿る時に, カウントを全て合算すればいい
    val G = Array.fill(N+1)(new ArrayBuffer[Int]())
    for (_ <- 0 until (N - 1)) {
      val a, b = sc.nextInt()
      G(a).append(b)
      G(b).append(a)
    }
    val P = Array.fill(Q, 2)(sc.nextInt())
    val C = new Array[Int](N+1)
    P.foreach { case Array(p, x) => C(p) += x }

    def solve(V: Int, G: Array[ArrayBuffer[Int]], C: Array[Int]): Array[Int] = {
      val visit = new Array[Boolean](V+1)
      def bfs(queue: Queue[Int]): Unit =
        if (queue.nonEmpty) {
          val u = queue.head
          val vertexes = G(u).filter(v => !visit(v))
          vertexes.foreach(v => {
            visit(u) = true
            C(v) += C(u)
          })
          bfs(vertexes.foldLeft(queue.tail)((queue, v) => queue.enqueue(v)))
        }
      bfs(Queue(1))
      C
    }

    val r = solve(N, G, C).tail.mkString(" ")
    println(r)
  }

}


import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    solve2
  }

  def solve2(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, q = sc.nextInt
    val to = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer.empty[Int])

    for (i <- 0 until n - 1) {
      val a = sc.nextInt - 1
      val b = sc.nextInt - 1
      to(a).append(b)
      to(b).append(a)
    }

    val ans = Array.fill[Long](n)(0L)
    for (i <- 0 until q) {
      val p = sc.nextInt - 1
      val x = sc.nextInt
      ans(p) += x
    }

    var stack = scala.collection.mutable.Stack[Int](0)
    val isVisited = Array.fill[Boolean](n)(false)
    while (stack.nonEmpty) {
      val top = stack.pop()
      isVisited(top) = true
      for (next <- to(top); if (!isVisited(next))) {
        ans(next) += ans(top)
        stack.push(next)
      }
    }
    println(ans.mkString(" "))
  }

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, q = sc.nextInt
    val to = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer.empty[Int])

    for (i <- 0 until n - 1) {
      val a = sc.nextInt - 1
      val b = sc.nextInt - 1
      to(a).append(b)
      to(b).append(a)
    }

    val ans = Array.fill[Long](n)(0L)
    for (i <- 0 until q) {
      val p = sc.nextInt - 1
      val x = sc.nextInt
      ans(p) += x
    }

    def dfs(v: Int, p: Int = -1): Unit = {
      for (u <- to(v)) {
        if (u != p) {
          ans(u) += ans(v)
          dfs(u, v)
        }
      }
    }

    dfs(0, -1)

    println(ans.mkString(" "))
  }
}


import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    solve
  }

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, q = sc.nextInt
    val to = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer.empty[Int])

    for (i <- 0 until n - 1) {
      val a = sc.nextInt - 1
      val b = sc.nextInt - 1
      to(a).+=(b)
      to(b).+=(a)
    }

    val ans = Array.fill[Long](n)(0L)
    for (i <- 0 until q) {
      val p = sc.nextInt - 1
      val x = sc.nextInt
      ans(p) += x
    }

    def dfs(v: Int, p: Int = -1): Unit = {
      for (u <- to(v)) {
        if (u != p) {
          ans(u) += ans(v)
          dfs(u, v)
        }
      }
    }

    dfs(0, -1)

    println(ans.mkString(" "))
  }
}


import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    solve
  }

  def solve(): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n, q = sc.nextInt
    val to = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer.empty[Int])

    for (i <- 0 until n - 1) {
      val a = sc.nextInt - 1
      val b = sc.nextInt - 1
      to(a).+=(b)
      to(b).+=(a)
    }

    val ans = Array.fill[Int](n)(0)
    for (i <- 0 until q) {
      val p = sc.nextInt - 1
      val x = sc.nextInt
      ans(p) += x
    }

    def dfs(v: Int, p: Int = -1): Unit = {
      for (u <- to(v)) {
        if (u != p) {
          ans(u) += ans(v)
          dfs(u, v)
        }
      }
    }

    dfs(0, -1)

    val pw = new java.io.PrintWriter(System.out)
    for (i <- 0 until n) {
      pw.println(ans(i))
    }
    pw.flush
  }
}


import scala.io.StdIn._
import scala.collection.mutable.ArrayBuffer
object Main extends App {
  val sr = new StdinReader
  val n, q = sr.nextInt

  val edges: Array[ArrayBuffer[Int]] = Array.tabulate(n + 1)(_ => new ArrayBuffer[Int]())
  (1 to n - 1).foreach {i =>
    val a, b = sr.nextInt
    edges(a) += b
    edges(b) += a
  }

  val vs = new Array[Long](n + 1)
  (1 to q).foreach {i =>
    val p, x = sr.nextInt
    vs(p) += x
  }

  def check(checks: List[Int]): Unit = {
    if (checks.nonEmpty) {
      check(checks.flatMap { i =>
        edges(i).foreach {v =>
          vs(v) += vs(i)
          edges(v) -= i
        }
        edges(i)
      })
    }
  }
  check(List(1))

  println(vs.tail.mkString(" "))
}

class StdinReader {
  val is = System.in
  val buffer = new Array[Byte](1024 * 1024)
  var size = 0
  var pos = 0

  private def readByte: Byte = {
    if (pos >= size) {
      pos = 0;
      size = is.read(buffer);
    }
    if (size < 0) -1
    else {
      val ret = buffer(pos)
      pos += 1
      ret
    }
  }

  // support single byte char only
  def next: String = {
    @scala.annotation.tailrec
    def r(sb: StringBuilder, reading: Boolean): String = {
      readByte match {
        case b if ('!' <= b && b <= '~') => r(sb.append(b.asInstanceOf[Char]), true)
        case _ => if (reading) sb.toString else r(sb, false)
      }
    }
    r(new StringBuilder, false)
  }

  def nextInt: Int = {
    @scala.annotation.tailrec
    def r(i: Int, reading: Boolean): Int = {
      readByte match {
        case '-' => r(i * -1, true)
        case b if '0' <= b && b <= '9' => r(i * 10 + (b - '0'), true)
        case _ => if (reading) i else r(i, false)
      }
    }
    r(0, false)
  }
}


import scala.io.StdIn._
import scala.collection.mutable.ArrayBuffer
object Main extends App {
  val Array(n, q) = readLine.split(" ").map(_.toInt)

  val edges: Array[ArrayBuffer[Int]] = Array.tabulate(n + 1)(_ => new ArrayBuffer[Int]())
  (1 to n - 1).foreach {i =>
    val Array(a, b) = readLine.split(" ").map(_.toInt)
    edges(a) += b
    edges(b) += a
  }

  val vs = new Array[Long](n + 1)
  (1 to q).foreach {i =>
    val Array(p, x) = readLine.split(" ").map(_.toInt)
    vs(p) += x
  }

  def check(checks: List[Int]): Unit = {
    if (checks.nonEmpty) {
      check(checks.flatMap { i =>
        edges(i).foreach {v =>
          vs(v) += vs(i)
          edges(v) -= i
        }
        edges(i)
      })
    }
  }
  check(List(1))

  println(vs.tail.mkString(" "))
}


object Main {
  def main(args: Array[String]) {
    val input = io.Source.stdin.getLines().mkString("\n");
    println(solve(input))

    def solve(input: String): String = {
      val nq :: list = input.split("\n").toList
      val (n, _) = spiltTwoInt(nq)
      val abs = list.take(n - 1).map(spiltTwoInt).sortBy(_._1)
      val qs = list.drop(n - 1).map(spiltTwoInt)

      val temp: Vector[Int] = qs.foldLeft(Vector.fill(n)(0)) {
        case (acc, (p, x)) =>
          val current = acc(p - 1)
          acc.updated(p - 1, x + current)
      }
      abs
        .foldLeft(temp) {
          case (acc, (a, b)) =>
            val curent = acc(b - 1)
            acc.updated(b - 1, curent + acc(a - 1))
        }
        .mkString(" ")
    }
  }

  def spiltTwoInt(s: String): (Int, Int) = {
    val res = s.split(" ").map(_.toInt)
    (res(0), res(1))
  }
}


object Main {
  def main(args: Array[String]) {
    val input = io.Source.stdin.getLines().mkString("\n");
    println(solve(input))

    def solve(input: String): String = {
      val nq :: list = input.split("\n").toList
      val (n, _) = spiltTwoInt(nq)
      val abs = list.take(n - 1).map(spiltTwoInt).sortBy(_._1)
      val qs = list.drop(n - 1).map(spiltTwoInt)

      val temp = qs.foldLeft(Seq.fill(n)(0)) {
        case (acc, (p, x)) =>
          val current = acc(p - 1)
          acc.updated(p - 1, x + current)
      }
      abs
        .foldLeft(temp) {
          case (acc, (a, b)) =>
            val curent = acc(b - 1)
            acc.updated(b - 1, curent + acc(a - 1))
        }
        .mkString(" ")
    }
  }

  def spiltTwoInt(s: String): (Int, Int) = {
    val res = s.split(" ").map(_.toInt)
    (res(0), res(1))
  }
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt()
  var edges: Array[Array[Int]] = Array.fill(N+1)(Array())
  var counters: Array[Long] = Array.fill(N+1)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt()
    edges(a) = edges(a) ++ Array(b)
    edges(b) = edges(b) ++ Array(a)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
    counters(p) += x
  }

  var visited = Array.fill(N+1)(false)
  def dfs(root: Int): Unit = {
    if(visited(root) == false) {
      visited(root) = true
      val children = edges(root)
      children.foreach { c =>
        if (visited(c) == false && c != root) {
          counters(c) += counters(root)
          dfs(c)
        }
      }
    }
  }
  dfs(1)
  print(counters.drop(1).mkString(" "))
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt()
  var edges: Array[Array[Int]] = Array.fill(N+1)(Array())
  var counters: Array[Long] = Array.fill(N+1)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt()
    edges(a) = edges(a) ++ Array(b)
    edges(b) = edges(b) ++ Array(a)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
    counters(p) += x
  }

  var visited = Array.fill(N+1)(false)
  def dfs(root: Int): Unit = {
    if(visited(root) == false) {
      visited(root) = true
      val children = edges(root)
      children.foreach { c =>
        if (visited(c) == false) {
          counters(c) += counters(root)
          dfs(c)
        }
      }
    }
  }
  dfs(1)

  print(counters.drop(1).mkString(" "))
}


object Main extends App {
  def dfs(root: Int, edges: Array[Array[Int]], visited: Array[Boolean], counters: Array[Long], rootCounters: Array[Long]): Unit = {
    if(visited(root) == false) {
      visited(root) = true
      counters(root) += rootCounters(root)
      val children = edges(root)
      if (children.length > 0) {
        children.foreach { c =>
          if (visited(c) == false) {
            counters(c) += counters(root)
            dfs(c, edges, visited, counters, rootCounters)
          }
        }
      }
    }
  }

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

  val N, Q = sc.nextInt()
  var edges: Array[Array[Int]] = Array.fill(N+1)(Array())
  var counters: Array[Long] = Array.fill(N+1)(0)
  val rootCounters: Array[Long] = Array.fill(N+1)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt()
    edges(a) = edges(a) ++ Array(b)
    edges(b) = edges(b) ++ Array(a)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
    rootCounters(p) += x
  }

  var visited = Array.fill(N+1)(false)
  dfs(1, edges, visited, counters, rootCounters)

  print(counters.drop(1).mkString(" "))
}


import scala.collection.mutable.ArrayBuffer

object Main extends App {
  def dfs(root: Int, edges: Array[ArrayBuffer[Int]], visited: Array[Boolean], counters: Array[Long]): Unit = {
    if(visited(root) == false) {
      visited(root) = true
      val children = edges(root)
      if (children.length > 0) {
        children.foreach { c =>
          if (visited(c) == false) {
            counters(c) += counters(root)
            dfs(c, edges, visited, counters)
          }
        }
      }
    }
  }

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

  val N, Q = sc.nextInt()
  var edges: Array[ArrayBuffer[Int]] = Array.fill(N+1)(ArrayBuffer[Int]())
  var operations: Array[(Int, Int)] = Array.fill(Q)((0, 0))
  var counters: Array[Long] = Array.fill(N+1)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt()
    edges(a).append(b)
    edges(b).append(a)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
  	operations(q-1) = (p, x)
  }

  var visited = Array.fill(N+1)(false)

  operations.foreach{ case (p, x) =>
    counters(p) += x
  }

  dfs(1, edges, visited, counters)

  print(counters.drop(1).mkString(" "))
}


object Main extends App {
  def dfs(root: Int, edges: Array[Array[Int]], visited: Array[Boolean], counters: Array[Long]): Unit = {
    if(visited(root-1) == false) {
      visited(root - 1) = true
      val children = edges(root - 1)
      children.foreach { c =>
        if (visited(c - 1) == false) {
          counters(c - 1) += counters(root - 1)
          dfs(c, edges, visited, counters)
        }
      }
    }
  }

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

  val N, Q = sc.nextInt()
  var edges: Array[Array[Int]] = Array.fill(N)(Array())
  var operations: Array[(Int, Int)] = Array.fill(Q)((0, 0))
  var counters: Array[Long] = Array.fill(N)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt()
    edges(a-1) = edges(a-1) ++ Array(b)
    edges(b-1) = edges(b-1) ++ Array(a)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
  	operations(q-1) = (p, x)
  }

  var visited = Array.fill(N)(false)

  operations.foreach{ case (p, x) =>
    counters(p-1) += x
  }

  dfs(1, edges, visited, counters)

  print(counters.mkString(" "))
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt()
  var nodes: Map[Int, Int] = Array().toMap
  var operations: Array[(Int, Int)] = Array.fill(Q)((0, 0))
  var counters: Array[Long] = Array.fill(N)(0)

  (1 to N-1).foreach { _ =>
    val p, c = sc.nextInt()
    nodes = nodes ++ Map(c -> p)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
  	operations(q-1) = (p, x)
  }

  operations.foreach{ case (p, x) =>
    counters(p-1) += x
  }

  (2 to N).foreach { c =>
    val p = nodes(c)
    counters(c-1) += counters(p-1)
  }

  print(counters.mkString(" "))
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt()
  var nodes: Map[Int, Int] = Array().toMap
  var operations: Array[(Int, Int)] = Array.fill(Q)((0, 0))
  var counters = Array.fill(N)(0)

  (1 to N-1).foreach { _ =>
    val p, c = sc.nextInt()
    nodes = nodes ++ Map(c -> p)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
  	operations(q-1) = (p, x)
  }

  operations.foreach{ case (p, x) =>
    counters(p-1) += x
  }

  (2 to N).foreach { c =>
    val p = nodes.get(c)
    if (p.isDefined) {
      counters(c - 1) += counters(p.get - 1)
    }
  }

  print(counters.mkString(" "))
}


object Main extends App {
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt()
  var nodes: Map[Int, Int] = Array().toMap
  var operations: Array[(Int, Int)] = Array.fill(Q)((0, 0))
  var counters = Array.fill(N)(0)

  (1 to N-1).foreach { _ =>
    val p, c = sc.nextInt()
    nodes = nodes ++ Map(c -> p)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
  	operations(q-1) = (p, x)
  }

  operations.foreach{ case (p, x) =>
    counters(p-1) += x
  }

  (2 to N).foreach { c =>
    val p = nodes.getOrElse(c, 1)
    counters(c-1) += counters(p-1)
  }

  print(counters.mkString(" "))
}


object Main extends App {
  def findChildren(root: Int, nodes: Array[(Int, Int)]) : Array[Int] = {
    var children: Array[Int] = Array()
    val subNodes = nodes.filter{case(a, _) => a>root}
    nodes.foreach{ case (x, y) =>
      if (x == root) {
        val thisChildren = findChildren(y, subNodes)
        children = children ++ thisChildren
      }
    }
    return children ++ Array(root)
  }
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt()
  var nodes: Map[Int, Int] = Array().toMap
  var operations: Array[(Int, Int)] = Array.fill(Q)((0, 0))
  var counters = Array.fill(N)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt()
    val (parent, child) = if (a < b) {(a, b)} else {(b, a)}
    nodes = nodes ++ Map(child -> parent)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
  	operations(q-1) = (p, x)
  }

  operations.foreach{ case (p, x) =>
    counters(p-1) += x
  }

  (2 to N).foreach { c =>
    val p = nodes(c)
    counters(c-1) += counters(p-1)
  }

  print(counters.mkString(" "))
}


object Main extends App {
  def findChildren(root: Int, nodes: Array[(Int, Int)]) : Array[Int] = {
    var children: Array[Int] = Array()
    val subNodes = nodes.filter{case(a, _) => a>root}
    nodes.foreach{ case (x, y) =>
      if (x == root) {
        val thisChildren = findChildren(y, subNodes)
        children = children ++ thisChildren
      }
    }
    return children ++ Array(root)
  }
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt()
  var nodes: Array[(Int, Int)] = Array.fill(N-1)((0, 0))
  var operations: Array[(Int, Int)] = Array.fill(Q)((0, 0))
  var counters = Array.fill(N)(0)

  (1 to N-1).foreach { i =>
    val a, b = sc.nextInt()
    nodes(i-1) = (a, b)
  }

  (1 to Q).foreach{ q =>
    val p, x = sc.nextInt()
  	operations(q-1) = (p, x)
  }

  operations.foreach{ case (p, x) =>
    counters(p-1) += x
  }

  (1 to N).foreach { p =>
    val children = nodes.filter{case(a, _) => a == p}.map{case(_, b) => b}
    children.foreach{ q =>
      counters(q-1) += counters(p-1)
    }
  }

  print(counters.mkString(" "))
}


object Main extends App {
  def findChildren(root: Int, nodes: Array[(Int, Int)]) : Array[Int] = {
    var children: Array[Int] = Array()
    val subNodes = nodes.filter{case(a, _) => a>root}
    nodes.foreach{ case (x, y) =>
      if (x == root) {
        val thisChildren = findChildren(y, subNodes)
        children = children ++ thisChildren
      }
    }
    return children ++ Array(root)
  }
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt
  var nodes: Array[(Int, Int)] = Array()
  var operations: Array[(Int, Int)] = Array()
  var counters = Array.fill(N)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt
    nodes = nodes ++ Array((a, b))
  }

  (1 to Q).foreach{ _ =>
    val p, x = sc.nextInt
  	operations = operations ++ Array((p, x))
  }

  val parToChildren = (1 to N).map{ p =>
    p -> findChildren(p, nodes)
  }.toMap

  operations.foreach{ case (p, x) =>
    counters(p-1) += x
  }

  (1 to N).reverse.foreach { p =>
    val children = parToChildren(p)
    children.filter(_ != p).foreach { c =>
      counters(c-1) += counters(p-1)
    }
  }

  print(counters.mkString(" "))
}


object Main extends App {
  def findChildren(root: Int, nodes: Array[(Int, Int)]) : Array[Int] = {
    var children: Array[Int] = Array()
    val subNodes = nodes.filter{case(a, _) => a>root}
    nodes.foreach{ case (x, y) =>
      if (x == root) {
        val thisChildren = findChildren(y, subNodes)
        children = children ++ thisChildren
      }
    }
    return children ++ Array(root)
  }
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt
  var nodes: Array[(Int, Int)] = Array()
  var operations: Array[(Int, Int)] = Array()
  var counters = Array.fill(N)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt
    nodes = nodes ++ Array((a, b))
  }

  (1 to Q).foreach{ _ =>
    val p, x = sc.nextInt
  	operations = operations ++ Array((p, x))
  }

  val parToChildren = (1 to N).map{ p =>
    p -> findChildren(p, nodes)
  }.toMap

  operations.foreach{ case (p, x) =>
    counters(p-1) += x
  }

  (1 to N).reverse.foreach { p =>
    val children = findChildren(p, nodes)
    children.filter(_ != p).foreach { c =>
      counters(c-1) += counters(p-1)
    }
  }

  print(counters.mkString(" "))
}


import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N, Q = Integer.parseInt(sc.next)
    val G = Array.fill(N + 1)(ArrayBuffer[Int]())
    (0 until N - 1) foreach { _ =>
      val a, b = sc.nextInt()
      G(a).append(b)
      G(b).append(a)
    }

    val PtoX = Array.fill(N + 1)(0)
    (0 until Q).foreach(_ => PtoX(sc.nextInt) += sc.nextInt)

    val Counter = new Array[Long](N + 1)
    val visited = new Array[Boolean](N + 1)

    val stack = new scala.collection.mutable.Stack[Int]
    stack.push(1)
    while (stack.nonEmpty) {
      val u = stack.pop()
      visited(u) = true
      Counter(u) += PtoX(u)
      G(u).foreach { v =>
        if (!visited(v)) {
          stack.push(v)
          Counter(v) += Counter(u)
        }
      }
    }

    println(Counter.tail.mkString(" "))
  }
}


object Main extends App {
  def findChildren(root: Int, nodes: Array[(Int, Int)]) : Array[Int] = {
    var children: Array[Int] = Array()
    nodes.foreach{ case (x, y) =>
      if (x == root) {
        val thisChildren = findChildren(y, nodes)
        children = children ++ thisChildren
      }
    }
    return children ++ Array(root)
  }
  val sc = new java.util.Scanner(System.in)

  val N, Q = sc.nextInt
  var nodes: Array[(Int, Int)] = Array()
  var operations: Array[(Int, Int)] = Array()
  var counters = Array.fill(N)(0)

  (1 to N-1).foreach { _ =>
    val a, b = sc.nextInt
    nodes = nodes ++ Array((a, b))
  }

  (1 to Q).foreach{ _ =>
    val p, x = sc.nextInt
  	operations = operations ++ Array((p, x))
  }

  operations.foreach{ case (p, x) =>
    val subNodes = nodes.filter{case (p_, _) => p_ >=p}
    val children = findChildren(p, subNodes)
    children.foreach{ c =>
      counters(c-1) += x
    }
  }

  print(counters.mkString(" "))
}


import scala.collection.mutable
import scala.collection.mutable.{Stack, Queue}
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Main{
  def main(args: Array[String]) = {
   val arr1 = io.StdIn.readLine().split(' ')
    val N = arr1(0).toInt
    val Q = arr1(1).toInt
    val cTree = mutable.HashMap.empty[Int, ListBuffer[Int]]
    val vTree = mutable.HashMap.empty[Int, Long]

    (0 until N - 1).foreach {
      i =>
        val arr = io.StdIn.readLine().split(' ')
        val (a, b) = (arr(0).toInt, arr(1).toInt)

        if (cTree.contains(a)) {
          val arr = cTree(a)
          arr.append(b)
          vTree.update(b, 0L)
          cTree(a) = arr
        } else {
          vTree.update(a, 0L)
          vTree.update(b, 0L)
          cTree.update(a, ListBuffer(b))
        }
    }

    (0 until Q).foreach {
      i =>
        val arr = io.StdIn.readLine().split(' ')
        val (p, x) = (arr(0).toInt, arr(1).toLong)
        vTree(p) += x
    }

    var s = new mutable.Stack[Int]
    s.push(1)

    while (s.nonEmpty) {
      var p = s.pop()
      val list = cTree(p)

      list.foreach {
        pi =>
          if (cTree.contains(pi)) {
            // 次が根ノードなら
            s.push(pi)
            vTree(pi) += vTree(p)
          } else {
            // 次が葉ノードなら
            vTree(pi) += vTree(p)
          }
      }

    }

    vTree.toSeq.sortBy(_._1).foreach(i => println(i._2))
}
}


object Main {

  import scala.collection.mutable.ArrayBuffer

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

    val N, Q = sc.nextInt()
    val G = Array.fill(N+1)(ArrayBuffer[Int]())
    (0 until N - 1) foreach { _ =>
      val a, b = sc.nextInt()
      G(a).append(b)
      G(b).append(a)
    }
    val PtoX = new Array[Long](N+1)
    (0 until Q). foreach { _ =>
      val p, x = sc.nextInt()
      PtoX(p) += x
    }

    val Counter = new Array[Long](N+1)
    val visited = new Array[Boolean](N+1)

    val stack = new scala.collection.mutable.Stack[Int]
    stack.push(1)
    while (stack.nonEmpty) {
      val u = stack.pop()
      visited(u) = true
      val thisCount = PtoX(u)
      Counter(u) += thisCount
      G(u).foreach { v =>
        if (!visited(v)) {
          stack.push(v)
          Counter(v) += Counter(u)
        }
      }
    }

    println(Counter.tail.mkString(" "))
  }

}


object Main {

  import scala.collection.mutable.ArrayBuffer

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

    val N, Q = sc.nextInt()
    val G = Array.fill(N+1)(ArrayBuffer[Int]())
    (0 until N - 1) foreach { _ =>
      val a, b = sc.nextInt()
      G(a).append(b)
      G(b).append(a)
    }
    val PtoX = scala.collection.mutable.Map[Int, Long]()
    (0 until Q). foreach { _ =>
      val p, x = sc.nextInt()
      PtoX.update(p, PtoX.getOrElse(p, 0L) + x)
    }

    // i番目の頂点のカウンタ, 訪れていなければ-1
    val Counter = new Array[Long](N+1)

    val visited = new Array[Boolean](N+1)

    val stack = new scala.collection.mutable.Stack[Int]
    stack.push(1)
    while (stack.nonEmpty) {
      val u = stack.pop()
      visited(u) = true
      val thisCount = if (PtoX.contains(u)) PtoX(u) else 0L
      Counter(u) += thisCount
      G(u).foreach { v =>
        if (!visited(v)) {
          stack.push(v)
          Counter(v) += Counter(u)
        }
      }
    }

    println(Counter.tail.mkString(" "))
  }

}


object Main {

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

    val N, Q = sc.nextInt()
    val G = Array.fill[List[Int]](N+1)(Nil)
    (0 until N - 1) foreach { _ =>
      val a, b = sc.nextInt()
      G(a) = b :: G(a)
      G(b) = a :: G(b)
    }
    val PtoX = scala.collection.mutable.Map[Int, Long]()
    (0 until Q). foreach { _ =>
      val p, x = sc.nextInt()
      PtoX.update(p, PtoX.getOrElse(p, 0L) + x)
    }

    // i番目の頂点のカウンタ, 訪れていなければ-1
    val Counter = Array.fill(N+1)(-1L)

    def solve(): Unit = {
      def dfs(u: Int, count: Long): Unit = {
        var thisCount = if (PtoX.contains(u)) PtoX(u) else 0L
        val newCount = thisCount + count
        Counter(u) = newCount
        G(u) foreach { v =>
          if (Counter(v) < 0) {
            dfs(v, newCount)
          }
        }
      }
      dfs(1, 0)
    }

    solve()

    println(Counter.tail.mkString(" "))
  }

}


object Main {

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

    val N, Q = sc.nextInt()
    val G = Array.fill[List[Int]](N)(Nil)
    (0 until N - 1) foreach { _ =>
      val a, b = sc.nextInt()
      G(a-1) = b-1 :: G(a-1)
      G(b-1) = a-1 :: G(b-1)
    }
    val PtoX = scala.collection.mutable.Map[Int, Long]()
    (0 until Q). foreach { _ =>
      val p, x = sc.nextInt()
      PtoX.update(p-1, PtoX.getOrElse(p-1, 0L) + x)
    }

    // i番目の頂点のカウンタ, 訪れていなければ-1
    val Counter = Array.fill(N)(-1L)

    def solve(): Unit = {
      def dfs(u: Int, count: Long): Unit =
        if (Counter(u) < 0) {
          var thisCount = if (PtoX.contains(u)) PtoX(u) else 0
          Counter(u) = thisCount + count
          G(u) foreach { v =>
            dfs(v, count + thisCount)
          }
        }
      dfs(0, 0)
    }

    solve()

    println(Counter.mkString(" "))
  }

}


object Main {

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

    val N, Q = sc.nextInt()
    val G = Array.fill[List[Int]](N)(Nil)
    (0 until N - 1) foreach { _ =>
      val a, b = sc.nextInt()
      G(a-1) = b-1 :: G(a-1)
      G(b-1) = a-1 :: G(b-1)
    }
    val PtoX = (0 until Q). map { _ =>
      val p, x = sc.nextInt()
      (p-1, x)
    }. groupBy(_._1). mapValues(_.map(_._2).sum)

    // i番目の頂点のカウンタ, 訪れていなければ-1
    val Counter = Array.fill(N)(-1L)

    def solve(): Unit = {
      def dfs(u: Int, count: Long): Unit =
        if (Counter(u) < 0) {
          var thisCount = if (PtoX.contains(u)) PtoX(u) else 0
          Counter(u) = thisCount + count
          G(u) foreach { v =>
            dfs(v, count + thisCount)
          }
        }
      dfs(0, 0)
    }

    solve()

    println(Counter.mkString(" "))
  }

}


object Main {

  val INF = Int.MaxValue

  case class Edge(u: Int, v: Int, weight: Int)
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)

    val V, E, P = sc.nextInt()

    // つまり, 辺を通る時, Pは損失されているので
    // 重みからPを引いておく.
    // -{w(u,v) - P} を重みとした単一始点最短路問題を解く
    // また, 正閉路が存在する場合, w(u,v) - P > 0の場合, 無限にコインを増やすことができる
    // そのため, 閉路判定を行う必要がある
    val edges = (0 until E).foldLeft(Nil: List[Edge])((lst, _) => {
      val u, v, c = sc.nextInt()
      Edge(u, v, -(c - P)) :: lst
    })

    bellmanFord(V, edges, 1, V) match {
      case Some(score) => println(score)
      case None => println(-1)
    }
  }

  def bellmanFord(V: Int, edges: List[Edge], s: Int, t: Int): Option[Int] = {
    val d = Array.fill(V+1)(INF)

    d(s) = 0
    for {
      _ <- 0 until V - 1
      edge <- edges
    } if (d(edge.u) != INF && d(edge.v) > d(edge.u) + edge.weight) {
      d(edge.v) = d(edge.u) + edge.weight
    }
    val max = d(t)

    val negative = new Array[Boolean](V+1)
    for {
      _ <- 0 until V
      edge <- edges
    } if (d(edge.u) != INF && d(edge.v) > d(edge.u) + edge.weight) {
      d(edge.v) = d(edge.u) + edge.weight
      negative(edge.v) = true
    }

    if (!negative(V)) Some(-max max 0)
    else None
  }

}

Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  case class Entry(v: Int, c: Int)
  type G = Array[ArrayBuffer[Entry]]

  def solve(): Unit = {
    val N, M, P = ni()
    val g = Array.fill[ArrayBuffer[Entry]](N)(ArrayBuffer())
    REP(M) { _ =>
      val a, b = ni() - 1
      val c = ni()
      g(a) += Entry(b, c)
    }

    val INF = -1e18.toLong
    val dp = Array.fill[Long](N)(INF)
    dp(0) = 0
    var temp: Long = -1
    REP(2 * N) { i =>
      REP(N) { v =>
        REP(g(v).length) { j =>
          if (dp(v) != INF) {
            val u = g(v)(j)
            if (dp(u.v) < dp(v) + u.c - P) {
              dp(u.v) = dp(v) + u.c - P
            }
          }
        }
      }
      if (i == N - 1) temp = dp(N - 1)
    }
    if (dp(N - 1) == temp) {
      out.println(max(0, dp(N - 1)))
    } else {
      out.println(-1)
    }
  }
}