Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".

The first line contains the only number n (0 ≤ n ≤ 100) — the amount of #define constructions in the given program. Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax: #define name expression where   name — the macro name,  expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.  All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction. Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions. The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol. The length of any line from the input file does not exceed 100 characters.

Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".

4
#define sum  x + y
#define mul  a * b
#define div  a / b
#define expr sum + mul * div * mul
expr

3
#define SumSafe   (a+b)
#define DivUnsafe  a/b
#define DenominatorUnsafe  a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)

object DefiningMacros extends App {
  sealed trait Term
  sealed trait Expr

  case object LeftParen extends Term
  case object RightParen extends Term
  case class Operator(op: Char) extends Term

  case class Number(n: Int) extends Term with Expr
  case class Var(name: String) extends Term with Expr

  case class Paren(sub: Expr) extends Expr
  case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr

  object Term {
    def apply(s: String): Term = s match {
      case "(" => LeftParen
      case ")" => RightParen
      case _ if "+-*/" contains s(0) => Operator(s(0))
      case _ if Character.isLetter(s(0)) => Var(s)
      case _ if Character.isDigit(s(0)) => Number(s.toInt)
    }
  }

  object Expr {
    val preds = List(Character.isLetter _, Character.isDigit _)

    def getPriority(expr: Expr): Int = expr match {
      case Paren(_) => 1000
      case BinOp(op, _, _) => getPriority(op)
      case t: Term => getPriority(t: Term)
    }

    def getPriority(term: Term): Int = term match {
      case Number(_) => 1000
      case Var(_) => 1000
      case Operator(op) =>
        if (op == '+' || op == '-') 1
        else 2
      case _ => -1
    }

    def tokenize(expr: String): List[String] = {
      def loop(s: String, res: List[String]): List[String] = {
        if (s.length == 0) res.reverse
        else {
          val c = s(0)
          val pred = preds.find(_(c))
          if (pred == None)
            loop(s.drop(1), c.toString :: res)
          else {
            val (prefix, rest) = s.span(pred.get)
            loop(rest, prefix.mkString :: res)
          }
        }
      }
      loop(expr, Nil)
    }

    def toExpr(terms: List[Term]): Expr = {
      if (terms.length == 1) return terms(0).asInstanceOf[Expr]

      val levels = terms.scanLeft(0) { (lev: Int, t: Term) =>
        t match {
          case LeftParen => lev + 1
          case RightParen => lev - 1
          case _ => lev
        }
      }
      val pris = terms.map(getPriority _)
      val candidates = terms.zipWithIndex.zip(levels.zip(pris)).filter{
        case ((Operator(c), _), (0, _)) => true
        case _ => false
      }

      if (candidates.isEmpty)
        Paren(toExpr(terms.slice(1, terms.length - 1)))
      else {
        val spix = candidates.minBy {
          case ((_, i), (_, p)) => (p, -i)
        }._1._2
        val (pre, suf) = terms.splitAt(spix)
        val (l, rt, r) = (pre, suf.head, suf.tail)
        BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))
      }
    }

    def parse(expr: String): Expr = {
      val terms = tokenize(expr).map(Term.apply _)
      toExpr(terms)
    }
  }

  val mem = collection.mutable.Map[(String, Int, Char), Boolean]()

  def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {
    val thisPri = Expr.getPriority(expr)
    expr match {
      case Var(name) if macros contains name =>
        val mexpr = macros(name)
        if (parentPri > Expr.getPriority(mexpr) ||
            parentPri == Expr.getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) false
        else {
          if (!(mem contains (name, parentPri, parentOp)))
            mem((name, parentPri, parentOp)) = check(macros, mexpr, parentPri, parentOp)
          mem(name, parentPri, parentOp)
        }
      case BinOp(Operator(op), l, r) =>
        check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)
      case Paren(sub) => check(macros, sub, -1, '?')
      case _ => true
    }
  }

  import java.io._

  val re = new BufferedReader(new InputStreamReader(System.in))
  val n = re.readLine.toInt
  val defs = for (i <- 0 until n) yield {
    val l = re.readLine.trim
    val pairs = l.substring(l.indexOf("define") + 6).trim
    val ss = pairs.split(" ", 2)
    ss(0) -> ss(1).replace(" ", "")
  }
  val inputExpr = re.readLine.replace(" ", "")

  val macros = Map() ++ (for ((k, v) <- defs) yield k -> Expr.parse(v))
  val expr = Expr.parse(inputExpr)

//  println(macros)
//  println(expr)

  println(if (check(macros, expr, -1, '?')) "OK" else "Suspicious")
}

object P7E {
    import io.StdIn._

    val m = collection.mutable.Map[String, Int]().withDefaultValue(0)

    /* import util.parsing.combinator._
    object ExpParsers extends JavaTokenParsers {
        val factor = wholeNumber ^^^ 0 | ident ^^ m | paren
        val term = chainl1(factor, ("[*" + "/]").r ^^ {
            case "*" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 1 else 3
            case "/" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 1) 1 else 3
        })
        val expr = chainl1(term, "[+-]".r ^^ {
            case "+" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 3) 2 else 3
            case "-" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 2 else 3
        })
        val paren:Parser[Int] = "(" ~> expr <~ ")" ^^ {
            case 3 => 3
            case _ => 0
        }
        def apply(s:String) = parseAll(expr, s).get
    } */

    object ExpParsers {
        import util.matching._
        case class StringSlice(a:String, i:Int) extends CharSequence {
            def charAt(n:Int) = a(i + n)
            def length = a.size - i
            def subSequence(n1:Int, n2:Int) = a.substring(i + n1, i + n2)
            def from(n:Int) = StringSlice(a, i + n)
        }
        val re1 = " *([A-Za-z0-9_]+)".r
        val re2 = (" *([/" + "*])").r
        val re3 = " *([+-])".r
        val re4 = " *\\(".r
        val re5 = " *\\)".r
        def parseFactor(a:StringSlice):(StringSlice, Int) = {
            re1.findPrefixMatchOf(a) match {
                case Some(m1) => (a.from(m1.end), m(m1.group(1)))
                case None => parseParen(a)
            }
        }
        def parseTerm(a:StringSlice) = {
            def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {
                re2.findPrefixMatchOf(a1) match {
                    case Some(m1) => parseFactor(a1.from(m1.end)) match {
                        case (a2, r2) if m1.group(1) == "*" =>
                            parse1(a2, if (r1 < 2 && r2 < 2) 1 else 3)
                        case (a2, r2) if m1.group(1) == "/" =>
                            parse1(a2, if (r1 < 2 && r2 < 1) 1 else 3)
                    }
                    case None => (a1, r1)
                }
            }
            parseFactor(a) match { case (a1, r1) => parse1(a1, r1) }
        }
        def parseExpr(a:StringSlice) = {
            def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {
                re3.findPrefixMatchOf(a1) match {
                    case Some(m1) => parseTerm(a1.from(m1.end)) match {
                        case (a2, r2) if m1.group(1) == "+" =>
                            parse1(a2, if (r1 < 3 && r2 < 3) 2 else 3)
                        case (a2, r2) if m1.group(1) == "-" =>
                            parse1(a2, if (r1 < 3 && r2 < 2) 2 else 3)
                    }
                    case None => (a1, r1)
                }
            }
            parseTerm(a) match { case (a1, r1) => parse1(a1, r1) }
        }
        def parseParen(a:StringSlice) = {
            re4.findPrefixMatchOf(a) match {
                case Some(m1) => parseExpr(a.from(m1.end)) match {
                    case (a1, r1) => re5.findPrefixMatchOf(a1) match {
                        case Some(m2) =>
                            (a1.from(m2.end), if (r1 < 3) 0 else 3)
                    }
                }
            }
        }
        def apply(s:String) = parseExpr(StringSlice(s, 0))._2
    }

    def main(args : Array[String]) {
        val define = " *# *define +(.*?) +(.*)".r
        for (i <- 1 to readInt) {
            val define(name, exp) = readLine
            m(name) = ExpParsers(exp)
        }
        println(if (ExpParsers(readLine) == 3) "Suspicious" else "OK")
    }
}

object DefiningMacros extends App {

  import java.io._

  val re = new BufferedReader(new InputStreamReader(System.in))
  val n = re.readLine.toInt
  val defs = for (i <- 0 until n) yield {
    val l = re.readLine.trim
    val pairs = l.substring(l.indexOf("define") + 6).trim
    val ss = pairs.split(" ", 2)
    ss(0) -> ss(1).replace(" ", "")
  }
  val inputExpr = re.readLine.replace(" ", "")

  println("GA")
  println(defs)
  println(inputExpr)
}

object DefiningMacros extends App {
  sealed trait Term
  sealed trait Expr

  case object LeftParen extends Term
  case object RightParen extends Term
  case class Operator(op: Char) extends Term

  case class Number(n: Int) extends Term with Expr
  case class Var(name: String) extends Term with Expr

  case class Paren(sub: Expr) extends Expr
  case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr

  object Term {
    def apply(s: String): Term = s match {
      case "(" => LeftParen
      case ")" => RightParen
      case _ if "+-*/" contains s(0) => Operator(s(0))
      case _ if Character.isLetter(s(0)) => Var(s)
      case _ if Character.isDigit(s(0)) => Number(s.toInt)
    }
  }

  object Expr {
    val preds = List(Character.isLetter _, Character.isDigit _)

    def tokenize(expr: String): List[String] = {
      def loop(s: String, res: List[String]): List[String] = {
        if (s.length == 0) res.reverse
        else {
          val c = s(0)
          val pred = preds.find(_(c))
          if (pred == None)
            loop(s.drop(1), c.toString :: res)
          else {
            val (prefix, rest) = s.span(pred.get)
            loop(rest, prefix.mkString :: res)
          }
        }
      }
      loop(expr, Nil)
    }

    def toExpr(terms: List[Term]): Expr = {
      if (terms.length == 1) return terms(0).asInstanceOf[Expr]

      val levels = terms.scanLeft(0) { (lev: Int, t: Term) =>
        t match {
          case LeftParen => lev + 1
          case RightParen => lev - 1
          case _ => lev
        }
      }
      val spix = terms.zipWithIndex.zip(levels).find{
        case ((Operator(c), i), l) => l == 0
        case _ => false
      }

      if (spix == None) {
        Paren(toExpr(terms.slice(1, terms.length - 1)))
      }
      else {
        val (pre, suf) = terms.splitAt(spix.get._1._2)
        val (l, rt, r) = (pre, suf.head, suf.tail)
        BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))
      }
    }

    def parse(expr: String): Expr = {
      val terms = tokenize(expr).map(Term.apply _)
      toExpr(terms)
    }
  }

  def getPriority(expr: Expr) = expr match {
    case Paren(_) => 0
    case Number(_) => 1000
    case BinOp(Operator(op), _, _) =>
      if (op == '+' || op == '-') 1
      else 2
    case Var(_) => 1000
  }

  def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {
    val thisPri = getPriority(expr)
    expr match {
      case Var(name) if macros contains name =>
        val mexpr = macros(name)
        if (parentPri > getPriority(mexpr) ||
            parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) {
/*          println("this expr = " + expr)
          println("parent op = " + parentOp)
          println("parent pri = " + parentPri)
          println("this pri = " + getPriority(mexpr))*/
          false
        }
        else check(macros, mexpr, parentPri, parentOp)
      case BinOp(Operator(op), l, r) =>
        check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)
      case Paren(sub) => check(macros, sub, thisPri, '?')
      case _ => true
    }
  }

  import java.io._

  val re = new BufferedReader(new InputStreamReader(System.in))
  val n = re.readLine.toInt
  val defs = for (i <- 0 until n) yield {
    val l = re.readLine.trim
    val pairs = l.substring(l.indexOf("define") + 6).trim
    val ss = pairs.split(" ", 2)
    ss(0) -> ss(1).replace(" ", "")
  }
  val inputExpr = re.readLine.replace(" ", "")

  val macros = (Map() ++ defs).mapValues(Expr.parse _)
  val expr = Expr.parse(inputExpr)

  println(if (check(macros, expr, -1, '?')) "OK" else "Suspicious")
}

object DefiningMacros extends App {
  sealed trait Term
  sealed trait Expr

  case object LeftParen extends Term
  case object RightParen extends Term
  case class Operator(op: Char) extends Term

  case class Number(n: Int) extends Term with Expr
  case class Var(name: String) extends Term with Expr

  case class Paren(sub: Expr) extends Expr
  case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr

  object Term {
    def apply(s: String): Term = s match {
      case "(" => LeftParen
      case ")" => RightParen
      case _ if "+-*/" contains s(0) => Operator(s(0))
      case _ if Character.isLetter(s(0)) => Var(s)
      case _ if Character.isDigit(s(0)) => Number(s.toInt)
    }
  }

  object Expr {
    val preds = List(Character.isLetter _, Character.isDigit _)

    def tokenize(expr: String): List[String] = {
      def loop(s: String, res: List[String]): List[String] = {
        if (s.length == 0) res.reverse
        else {
          val c = s(0)
          val pred = preds.find(_(c))
          if (pred == None)
            loop(s.drop(1), c.toString :: res)
          else {
            val (prefix, rest) = s.span(pred.get)
            loop(rest, prefix.mkString :: res)
          }
        }
      }
      loop(expr, Nil)
    }

    def toExpr(terms: List[Term]): Expr = {
      if (terms.length == 1) return terms(0).asInstanceOf[Expr]

      val levels = terms.scanLeft(0) { (lev: Int, t: Term) =>
        t match {
          case LeftParen => lev + 1
          case RightParen => lev - 1
          case _ => lev
        }
      }
      val spix = terms.zipWithIndex.zip(levels).find{
        case ((Operator(c), i), l) => l == 0
        case _ => false
      }

      if (spix == None) {
        Paren(toExpr(terms.slice(1, terms.length - 1)))
      }
      else {
        val (pre, suf) = terms.splitAt(spix.get._1._2)
        val (l, rt, r) = (pre, suf.head, suf.tail)
        BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))
      }
    }

    def parse(expr: String): Expr = {
      val terms = tokenize(expr).map(Term.apply _)
      toExpr(terms)
    }
  }

  def getPriority(expr: Expr) = expr match {
    case Paren(_) => 1000
    case Number(_) => 1000
    case BinOp(Operator(op), _, _) =>
      if (op == '+' || op == '-') 1
      else 2
    case Var(_) => 1000
  }

  def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {
    val thisPri = getPriority(expr)
    expr match {
      case Var(name) if macros contains name =>
        val mexpr = macros(name)
        if (parentPri > getPriority(mexpr) ||
            parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) false
        else check(macros, mexpr, parentPri, parentOp)
      case BinOp(Operator(op), l, r) =>
        check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)
      case Paren(sub) => check(macros, sub, thisPri, '?')
      case _ => true
    }
  }

  import java.io._

  val re = new BufferedReader(new InputStreamReader(System.in))
  val n = re.readLine.toInt
  val defs = for (i <- 0 until n) yield {
    val l = re.readLine.trim
    val pairs = l.substring(l.indexOf("define") + 6).trim
    val ss = pairs.split(" ", 2)
    ss(0) -> ss(1).replace(" ", "")
  }
  val inputExpr = re.readLine.replace(" ", "")

  val macros = (Map() ++ defs).mapValues(Expr.parse _)
  val expr = Expr.parse(inputExpr)

  println(if (check(macros, expr, -1, '?')) "OK" else "Suspicious")
}

object DefiningMacros extends App {
  sealed trait Term
  sealed trait Expr

  case object LeftParen extends Term
  case object RightParen extends Term
  case class Operator(op: Char) extends Term

  case class Number(n: Int) extends Term with Expr
  case class Var(name: String) extends Term with Expr

  case class Paren(sub: Expr) extends Expr
  case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr

  object Term {
    def apply(s: String): Term = s match {
      case "(" => LeftParen
      case ")" => RightParen
      case _ if "+-*/" contains s(0) => Operator(s(0))
      case _ if Character.isLetter(s(0)) => Var(s)
      case _ if Character.isDigit(s(0)) => Number(s.toInt)
    }
  }

  object Expr {
    val preds = List(Character.isLetter _, Character.isDigit _)

    def tokenize(expr: String): List[String] = {
      def loop(s: String, res: List[String]): List[String] = {
        if (s.length == 0) res.reverse
        else {
          val c = s(0)
          val pred = preds.find(_(c))
          if (pred == None)
            loop(s.drop(1), c.toString :: res)
          else {
            val (prefix, rest) = s.span(pred.get)
            loop(rest, prefix.mkString :: res)
          }
        }
      }
      loop(expr, Nil)
    }

    def toExpr(terms: List[Term]): Expr = {
      if (terms.length == 1) return terms(0).asInstanceOf[Expr]

      val levels = terms.scanLeft(0) { (lev: Int, t: Term) =>
        t match {
          case LeftParen => lev + 1
          case RightParen => lev - 1
          case _ => lev
        }
      }
      val spix = terms.zipWithIndex.zip(levels).find{
        case ((Operator(c), i), l) => l == 0
        case _ => false
      }

      if (spix == None) {
        Paren(toExpr(terms.slice(1, terms.length - 1)))
      }
      else {
        val (pre, suf) = terms.splitAt(spix.get._1._2)
        val (l, rt, r) = (pre, suf.head, suf.tail)
        BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))
      }
    }

    def parse(expr: String): Expr = {
      val terms = tokenize(expr).map(Term.apply _)
      toExpr(terms)
    }
  }

  def getPriority(expr: Expr) = expr match {
    case Paren(_) => 1000
    case Number(_) => 1000
    case BinOp(Operator(op), _, _) =>
      if (op == '+' || op == '-') 1
      else 2
    case Var(_) => 1000
  }

  def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {
    val thisPri = getPriority(expr)
    expr match {
      case Var(name) if macros contains name =>
        val mexpr = macros(name)
        if (parentPri > getPriority(mexpr) ||
            parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) {
          println("this expr = " + expr)
          println("parent op = " + parentOp)
          println("parent pri = " + parentPri)
          println("this pri = " + getPriority(mexpr))
          false
        }
        else check(macros, mexpr, parentPri, parentOp)
      case BinOp(Operator(op), l, r) =>
        check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)
      case Paren(sub) => check(macros, sub, -1, '?')
      case _ => true
    }
  }

  import java.io._

  val re = new BufferedReader(new InputStreamReader(System.in))
  val n = re.readLine.toInt
  val defs = for (i <- 0 until n) yield {
    val l = re.readLine.trim
    val pairs = l.substring(l.indexOf("define") + 6).trim
    val ss = pairs.split(" ", 2)
    ss(0) -> ss(1).replace(" ", "")
  }
  val inputExpr = re.readLine.replace(" ", "")

  val macros = (Map() ++ defs).mapValues(Expr.parse _)
  val expr = Expr.parse(inputExpr)

  println(if (check(macros, expr, -1, '?')) "OK" else "Suspicious")
}

object DefiningMacros extends App {
  sealed trait Term
  sealed trait Expr

  case object LeftParen extends Term
  case object RightParen extends Term
  case class Operator(op: Char) extends Term

  case class Number(n: Int) extends Term with Expr
  case class Var(name: String) extends Term with Expr

  case class Paren(sub: Expr) extends Expr
  case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr

  object Term {
    def apply(s: String): Term = s match {
      case "(" => LeftParen
      case ")" => RightParen
      case _ if "+-*/" contains s(0) => Operator(s(0))
      case _ if Character.isLetter(s(0)) => Var(s)
      case _ if Character.isDigit(s(0)) => Number(s.toInt)
    }
  }

  object Expr {
    val preds = List(Character.isLetter _, Character.isDigit _)

    def tokenize(expr: String): List[String] = {
      def loop(s: String, res: List[String]): List[String] = {
        if (s.length == 0) res.reverse
        else {
          val c = s(0)
          val pred = preds.find(_(c))
          if (pred == None)
            loop(s.drop(1), c.toString :: res)
          else {
            val (prefix, rest) = s.span(pred.get)
            loop(rest, prefix.mkString :: res)
          }
        }
      }
      loop(expr, Nil)
    }

    def toExpr(terms: List[Term]): Expr = {
      if (terms.length == 1) return terms(0).asInstanceOf[Expr]

      val levels = terms.scanLeft(0) { (lev: Int, t: Term) =>
        t match {
          case LeftParen => lev + 1
          case RightParen => lev - 1
          case _ => lev
        }
      }
      val spix = terms.zipWithIndex.zip(levels).find{
        case ((Operator(c), i), l) => l == 0
        case _ => false
      }

      if (spix == None) {
        Paren(toExpr(terms.slice(1, terms.length - 1)))
      }
      else {
        val (pre, suf) = terms.splitAt(spix.get._1._2)
        val (l, rt, r) = (pre, suf.head, suf.tail)
        BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))
      }
    }

    def parse(expr: String): Expr = {
      val terms = tokenize(expr).map(Term.apply _)
      toExpr(terms)
    }
  }

  def getPriority(expr: Expr) = expr match {
    case Paren(_) => 1000
    case Number(_) => 1000
    case BinOp(Operator(op), _, _) =>
      if (op == '+' || op == '-') 1
      else 2
    case Var(_) => -1
  }

  def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {
    val thisPri = getPriority(expr)
    expr match {
      case Var(name) if macros contains name =>
        val mexpr = macros(name)
        if (parentPri > getPriority(mexpr) ||
            parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) false
        else check(macros, mexpr, parentPri, parentOp)
      case BinOp(Operator(op), l, r) =>
        check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)
      case Paren(sub) => check(macros, sub, thisPri, '?')
      case _ => true
    }
  }

  import java.io._

  val re = new BufferedReader(new InputStreamReader(System.in))
  val n = re.readLine.toInt
  val defs = for (i <- 0 until n) yield {
    val l = re.readLine.trim
    val pairs = l.substring(l.indexOf("define") + 6).trim
    val ss = pairs.split(" ", 2)
    ss(0) -> ss(1).replace(" ", "")
  }
  val inputExpr = re.readLine.replace(" ", "")

  val macros = (Map() ++ defs).mapValues(Expr.parse _)
  val expr = Expr.parse(inputExpr)

  println(if (check(macros, expr, -1, '?')) "OK" else "Suspicious")
}

object DefiningMacros extends App {
  sealed trait Term
  sealed trait Expr

  case object LeftParen extends Term
  case object RightParen extends Term
  case class Operator(op: Char) extends Term

  case class Number(n: Int) extends Term with Expr
  case class Var(name: String) extends Term with Expr

  case class Paren(sub: Expr) extends Expr
  case class BinOp(op: Operator, left: Expr, right: Expr) extends Expr

  object Term {
    def apply(s: String): Term = s match {
      case "(" => LeftParen
      case ")" => RightParen
      case _ if "+-*/" contains s(0) => Operator(s(0))
      case _ if Character.isLetter(s(0)) => Var(s)
      case _ if Character.isDigit(s(0)) => Number(s.toInt)
    }
  }

  object Expr {
    val preds = List(Character.isLetter _, Character.isDigit _)

    def tokenize(expr: String): List[String] = {
      def loop(s: String, res: List[String]): List[String] = {
        if (s.length == 0) res.reverse
        else {
          val c = s(0)
          val pred = preds.find(_(c))
          if (pred == None)
            loop(s.drop(1), c.toString :: res)
          else {
            val (prefix, rest) = s.span(pred.get)
            loop(rest, prefix.mkString :: res)
          }
        }
      }
      loop(expr, Nil)
    }

    def toExpr(terms: List[Term]): Expr = {
      if (terms.length == 1) return terms(0).asInstanceOf[Expr]

      val levels = terms.scanLeft(0) { (lev: Int, t: Term) =>
        t match {
          case LeftParen => lev + 1
          case RightParen => lev - 1
          case _ => lev
        }
      }
      val spix = terms.zipWithIndex.zip(levels).find{
        case ((Operator(c), i), l) => l == 0
        case _ => false
      }

      if (spix == None) {
        Paren(toExpr(terms.slice(1, terms.length - 1)))
      }
      else {
        val (pre, suf) = terms.splitAt(spix.get._1._2)
        val (l, rt, r) = (pre, suf.head, suf.tail)
        BinOp(rt.asInstanceOf[Operator], toExpr(l), toExpr(r))
      }
    }

    def parse(expr: String): Expr = {
      val terms = tokenize(expr).map(Term.apply _)
      toExpr(terms)
    }
  }

  def getPriority(expr: Expr) = expr match {
    case Paren(_) => 1000
    case Number(_) => 1000
    case BinOp(Operator(op), _, _) =>
      if (op == '+' || op == '-') 1
      else 2
    case Var(_) => 1000
  }

  def check(macros: Map[String, Expr], expr: Expr, parentPri: Int, parentOp: Char): Boolean = {
    val thisPri = getPriority(expr)
    expr match {
      case Var(name) if macros contains name =>
        val mexpr = macros(name)
        if (parentPri > getPriority(mexpr) ||
            parentPri == getPriority(mexpr) && (parentOp == '-' || parentOp == '/')) {
/*          println("this expr = " + expr)
          println("parent op = " + parentOp)
          println("parent pri = " + parentPri)
          println("this pri = " + getPriority(mexpr))*/
          false
        }
        else check(macros, mexpr, parentPri, parentOp)
      case BinOp(Operator(op), l, r) =>
        check(macros, l, thisPri, '?') && check(macros, r, thisPri, op)
      case Paren(sub) => check(macros, sub, -1, '?')
      case _ => true
    }
  }

  import java.io._

  val re = new BufferedReader(new InputStreamReader(System.in))
  val n = re.readLine.toInt
  val defs = for (i <- 0 until n) yield {
    val l = re.readLine.trim
    val pairs = l.substring(l.indexOf("define") + 6).trim
    val ss = pairs.split(" ", 2)
    ss(0) -> ss(1).replace(" ", "")
  }
  val inputExpr = re.readLine.replace(" ", "")

  val macros = (Map() ++ defs).mapValues(Expr.parse _)
  val expr = Expr.parse(inputExpr)

  println(if (check(macros, expr, -1, '?')) "OK" else "Suspicious")
}

object P7E {
    import io.StdIn._

    val m = collection.mutable.Map[String, Int]().withDefaultValue(0)

    /* import util.parsing.combinator._
    object ExpParsers extends JavaTokenParsers {
        val factor = wholeNumber ^^^ 0 | ident ^^ m | paren
        val term = chainl1(factor, ("[*" + "/]").r ^^ {
            case "*" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 1 else 3
            case "/" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 1) 1 else 3
        })
        val expr = chainl1(term, "[+-]".r ^^ {
            case "+" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 3) 2 else 3
            case "-" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 2 else 3
        })
        val paren:Parser[Int] = "(" ~> expr <~ ")" ^^ {
            case 3 => 3
            case _ => 0
        }
        def apply(s:String) = parseAll(expr, s).get
    } */

    object ExpParsers {
        import util.matching._
        case class StringSlice(a:String, i:Int) extends CharSequence {
            def charAt(n:Int) = a(i + n)
            def length = a.size - i
            def subSequence(n1:Int, n2:Int) = a.substring(i + n1, i + n2)
            def from(n:Int) = StringSlice(a, i + n)
        }
        val re1 = " *([A-Za-z0-9_]+)".r
        val re2 = (" *([/" + "*])").r
        val re3 = " *([+-])".r
        val re4 = " *\\(".r
        val re5 = " *\\)".r
        def parseFactor(a:StringSlice):(StringSlice, Int) = {
            re1.findPrefixMatchOf(a) match {
                case Some(m1) => (a.from(m1.end), m(m1.group(1)))
                case None => parseParen(a)
            }
        }
        def parseTerm(a:StringSlice) = {
            def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {
                re2.findPrefixMatchOf(a1) match {
                    case Some(m1) => parseFactor(a1.from(m1.end)) match {
                        case (a2, r2) if m1.group(1) == "*" =>
                            parse1(a2, if (r1 < 3 && r2 < 2) 1 else 3)
                        case (a2, r2) if m1.group(1) == "/" =>
                            parse1(a2, if (r1 < 3 && r2 < 1) 1 else 3)
                    }
                    case None => (a1, r1)
                }
            }
            parseFactor(a) match { case (a1, r1) => parse1(a1, r1) }
        }
        def parseExpr(a:StringSlice) = {
            def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {
                re3.findPrefixMatchOf(a1) match {
                    case Some(m1) => parseTerm(a1.from(m1.end)) match {
                        case (a2, r2) if m1.group(1) == "+" =>
                            parse1(a2, if (r1 < 3 && r2 < 3) 2 else 3)
                        case (a2, r2) if m1.group(1) == "-" =>
                            parse1(a2, if (r1 < 3 && r2 < 2) 2 else 3)
                    }
                    case None => (a1, r1)
                }
            }
            parseTerm(a) match { case (a1, r1) => parse1(a1, r1) }
        }
        def parseParen(a:StringSlice) = {
            re4.findPrefixMatchOf(a) match {
                case Some(m1) => parseExpr(a.from(m1.end)) match {
                    case (a1, r1) => re5.findPrefixMatchOf(a1) match {
                        case Some(m2) =>
                            (a1.from(m2.end), if (r1 < 3) 0 else 3)
                    }
                }
            }
        }
        def apply(s:String) = parseExpr(StringSlice(s, 0))._2
    }

    def main(args : Array[String]) {
        val define = " *# *define *(.*?) *(.*)".r
        for (i <- 1 to readInt) {
            val define(name, exp) = readLine
            m(name) = ExpParsers(exp)
        }
        println(if (ExpParsers(readLine) == 3) "Suspicious" else "OK")
    }
}

object P7E {
    import io.StdIn._

    val m = collection.mutable.Map[String, Int]().withDefaultValue(0)

    /* import util.parsing.combinator._
    object ExpParsers extends JavaTokenParsers {
        val factor = wholeNumber ^^^ 0 | ident ^^ m | paren
        val term = chainl1(factor, ("[*" + "/]").r ^^ {
            case "*" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 1 else 3
            case "/" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 1) 1 else 3
        })
        val expr = chainl1(term, "[+-]".r ^^ {
            case "+" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 3) 2 else 3
            case "-" => (a1:Int, a2:Int) => if (a1 < 3 && a2 < 2) 2 else 3
        })
        val paren:Parser[Int] = "(" ~> expr <~ ")" ^^ {
            case 3 => 3
            case _ => 0
        }
        def apply(s:String) = parseAll(expr, s).get
    } */

    object ExpParsers {
        import util.matching._
        case class StringSlice(a:String, i:Int) extends CharSequence {
            def charAt(n:Int) = a(i + n)
            def length = a.size - i
            def subSequence(n1:Int, n2:Int) = a.substring(i + n1, i + n2)
            def from(n:Int) = StringSlice(a, i + n)
        }
        val re1 = " *([A-Za-z0-9_]+)".r
        val re2 = (" *([/" + "*])").r
        val re3 = " *([+-])".r
        val re4 = " *\\(".r
        val re5 = " *\\)".r
        def parseFactor(a:StringSlice):(StringSlice, Int) = {
            re1.findPrefixMatchOf(a) match {
                case Some(m1) => (a.from(m1.end), m(m1.group(1)))
                case None => parseParen(a)
            }
        }
        def parseTerm(a:StringSlice) = {
            def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {
                re2.findPrefixMatchOf(a1) match {
                    case Some(m1) => parseFactor(a1.from(m1.end)) match {
                        case (a2, r2) if m1.group(1) == "*" =>
                            parse1(a2, if (r1 < 3 && r2 < 2) 1 else 3)
                        case (a2, r2) if m1.group(1) == "/" =>
                            parse1(a2, if (r1 < 3 && r2 < 1) 1 else 3)
                    }
                    case None => (a1, r1)
                }
            }
            parseFactor(a) match { case (a1, r1) => parse1(a1, r1) }
        }
        def parseExpr(a:StringSlice) = {
            def parse1(a1:StringSlice, r1:Int):(StringSlice, Int) = {
                re3.findPrefixMatchOf(a1) match {
                    case Some(m1) => parseTerm(a1.from(m1.end)) match {
                        case (a2, r2) if m1.group(1) == "+" =>
                            parse1(a2, if (r1 < 3 && r2 < 3) 2 else 3)
                        case (a2, r2) if m1.group(1) == "-" =>
                            parse1(a2, if (r1 < 3 && r2 < 2) 2 else 3)
                    }
                    case None => (a1, r1)
                }
            }
            parseTerm(a) match { case (a1, r1) => parse1(a1, r1) }
        }
        def parseParen(a:StringSlice) = {
            re4.findPrefixMatchOf(a) match {
                case Some(m1) => parseExpr(a.from(m1.end)) match {
                    case (a1, r1) => re5.findPrefixMatchOf(a1) match {
                        case Some(m2) =>
                            (a1.from(m2.end), if (r1 < 3) 0 else 3)
                    }
                }
            }
        }
        def apply(s:String) = parseExpr(StringSlice(s, 0))._2
    }

    def main(args : Array[String]) {
        val define = " *# *define +(.*?) +(.*)".r
        for (i <- 1 to readInt) {
            val define(name, exp) = readLine
            m(name) = ExpParsers(exp)
        }
        println(if (ExpParsers(readLine) == 3) "Suspicious" else "OK")
    }
}


DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:  where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:  ;  edge  if and only if , and edge ;  the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.

The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.

Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.

NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal.

import java.util.Scanner

/**
 * Created by hama_du on 2014/09/01.
 */
object ProblemA extends App {
  val in = new Scanner(System.in)
  val n = in.nextInt()
  val m = in.nextInt()
  val v = (0 until n).map(_ => in.nextInt).toArray
  val edges = (0 until m).map(_ => (in.nextInt()-1, in.nextInt()-1, in.nextInt())).toArray

  println(solve(v, edges))

  def solve(v: Array[Int], edges: Array[(Int,Int,Int)]): Double = {
    if (edges.length == 0) {
      0
    } else {
      edges.map(edge => (v(edge._1) + v(edge._2) + 0.0d) / edge._3 ).max
    }
  }
}


After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.

The first line contains two space-separated integers n and x (1 ≤ n ≤ 1000, 0 ≤ x ≤ 109). Each of the next n lines contains a character '+' or '-', and an integer di, separated by a space (1 ≤ di ≤ 109). Record "+ di" in i-th line means that a carrier with di ice cream packs occupies i-th place from the start of the queue, and record "- di" means that a child who wants to take di packs stands in i-th place.

Print two space-separated integers — number of ice cream packs left after all operations, and number of kids that left the house in distress.

NoteConsider the first sample.  Initially Kay and Gerda have 7 packs of ice cream.  Carrier brings 5 more, so now they have 12 packs.  A kid asks for 10 packs and receives them. There are only 2 packs remaining.  Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed.  Carrier bring 40 packs, now Kay and Gerda have 42 packs.  Kid asks for 20 packs and receives them. There are 22 packs remaining.

import scala.io.StdIn._

object _359A extends App {
  val input = readLine().split(" ").map(_.toInt)
  val (n, x) = (input(0), input(1))
  var acc: Long = x
  var dis = 0
  for (i <- 1 to n) {
    val input = readLine().split(" ")
    var inc: Long = input(1).toInt
    inc = if (input(0) == "+") inc else -inc
    if (acc + inc < 0) dis += 1
    else acc += inc
  }
  println(acc + " " + dis)
}

import java.util.Scanner

import scala.collection.immutable.HashSet
import scala.io.StdIn

/**
  * Created by shvedchikov on 13.01.16.
  */
object Codeforces extends App {
  override def main(args: Array[String]) {
    iceCream()
  }

  //http://codeforces.com/problemset/problem/686/A
  def iceCream(): Unit = {

    case class Status(iceCreamsCount: Long, sadChildrenCount: Long) {
      override def toString: String = s"$iceCreamsCount $sadChildrenCount"
    }

    val Array(n, x) = StdIn.readLine().split(" ").map(_.toLong)
    val result = (1L to n)
      .map(_ => StdIn.readLine().split(" ") match { case Array(sign, count) => (sign, count.toLong) })
      .foldLeft(Status(x, 0))((status, request) => {
        val (sign, count) = request
        sign match {
          case "+" =>
            status.copy(iceCreamsCount = status.iceCreamsCount + count)
          case "-" if status.iceCreamsCount < count =>
            status.copy(sadChildrenCount = status.sadChildrenCount + 1)
          case "-" if status.iceCreamsCount >= count =>
            status.copy(iceCreamsCount = status.iceCreamsCount - count)
        }
      })
    print(result)
  }

}

object Solution {
    def re(ns:List[Long],x:Long,d:Int):Unit =
      if (ns.isEmpty) println(s"$x $d")
      else if (ns.head > 0) re(ns.tail,x+ns.head,d)
      else if (-ns.head > x) re(ns.tail,x,d+1)
      else re(ns.tail,x+ns.head,d)
    def main(args: Array[String]) {
        val nx = readLine.split(" ").map(_.toLong)
        val ns = (0 until nx(0).toInt).map(_=>{
          val pv = readLine.split(" ")
          if (pv(0)=="+") pv(1).toLong else -pv(1).toLong
        }).toList
        re(ns,nx(1),0)
    }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val Array(n, x) = lines.next().split(' ').map(_.toInt)
  val (l, u) = lines.take(n).foldLeft(x.toLong, 0) {
    case((left, unh), str) if str.startsWith("+") => (left + str.drop(2).toInt, unh)
    case((left, unh), str) if str.startsWith("-") =>
      val count = str.drop(2).toInt
      if (count > left)
        (left, unh + 1)
      else
        (left - count, unh)
  }
  println(s"$l $u")
}

object A686 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, x) = readLongs(2)
    val input = Array.fill(n.toInt){
      val tl = tokenizeLine
      (tl.nextToken, tl.nextToken.toLong)
    }
    var ice = x
    var left = 0L

    for(i <- 0 until n.toInt){
      if(input(i)._1 == "+") {
        ice += input(i)._2
      } else {
        if(ice >= input(i)._2) {
          ice -= input(i)._2
        } else {
          left += 1
        }
      }
    }

    println(s"$ice $left")
  }
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _686A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    var x = read[Long]
    var unhappy = 0

    repeat(n) {
      read[(Char, Long)] match {
        case ('+', i) => x += i
        case ('-', i) if i <= x => x -= i
        case _ => unhappy += 1
      }
    }

    write(x, unhappy)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import java.util.Scanner

object Main{
  // val n = sc.nextInt()
  // val s = sc.nextLine()
  // val str = sc.next()

  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val x = sc.nextInt()
    sc.nextLine()

    var ice: Long = x
    var distman = 0
    for(k <- 1 to n){
      val query = sc.next()
      val d = sc.nextInt()
      sc.nextLine()

      if(query == "+")
        ice += d
      else{
        if(ice >= d)
          ice -= d
        else
          distman += 1
      }
    }

    println(ice + " " + distman)
  }
}

object Main{
  def main(args: Array[String]) {

    val temp = scala.io.StdIn.readLine().split(" ").map(x => x.toInt)
    val n = temp(0); val x = temp(1)

    var children = 0
    var ice = x.toLong

    for(x <- 1 to n){
      val temp = scala.io.StdIn.readLine().split(" ")
      val b = temp(0); val d = temp(1).toLong

      b match {
        case "+" => ice = ice + d
        case "-" => if (ice >= d) {ice = ice - d} else {children = children + 1}
      }
    }

    println(ice + " " + children)

  }
}

import java.util.Scanner

import scala.collection.immutable.HashSet
import scala.io.StdIn

/**
  * Created by shvedchikov on 13.01.16.
  */
object Codeforces extends App {
  override def main(args: Array[String]) {
    iceCream()
  }

  //http://codeforces.com/problemset/problem/686/A
  def iceCream(): Unit = {

    case class Status(iceCreamsCount: Int, sadChildrenCount: Int) {
      override def toString: String = s"$iceCreamsCount $sadChildrenCount"
    }

    val Array(n, x) = StdIn.readLine().split(" ").map(_.toInt)
    val result = (1 to n)
      .map(_ => StdIn.readLine().split(" ") match { case Array(sign, count) => (sign, count.toInt) })
      .foldLeft(Status(x, 0))((status, request) => {
        val (sign, count) = request
        sign match {
          case "+" =>
            status.copy(iceCreamsCount = status.iceCreamsCount + count)
          case "-" if status.iceCreamsCount < count =>
            status.copy(sadChildrenCount = status.sadChildrenCount + 1)
          case "-" if status.iceCreamsCount >= count =>
            status.copy(iceCreamsCount = status.iceCreamsCount - count)
        }
      })
    print(result)
  }

}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val Array(n, x) = lines.next().split(' ').map(_.toInt)
  val (l, u) = lines.take(n).foldLeft(x, 0) {
    case((left, unh), str) if str.startsWith("+") => (left + str.drop(2).toInt, unh)
    case((left, unh), str) if str.startsWith("-") =>
      val count = str.drop(2).toInt
      if (count > left)
        (left, unh + 1)
      else
        (left - count, unh)
  }
  println(s"$l $u")
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _686A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    var x = read[Int]
    var unhappy = 0

    repeat(n) {
      read[(Char, Int)] match {
        case ('+', i) => x += i
        case ('-', i) if i <= x => x -= i
        case _ => unhappy += 1
      }
    }

    write(x, unhappy)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeLine(obj: Any*): this.type = {
    if (obj.isEmpty) printer.println() else obj foreach printer.println
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object Main{
  def main(args: Array[String]) {

    val temp = scala.io.StdIn.readLine().split(" ").map(x => x.toInt)
    val n = temp(0); val x = temp(1)

    var children = 0
    var ice = x

    for(x <- 1 to n){
      val temp = scala.io.StdIn.readLine().split(" ")
      val b = temp(0); val d = temp(1).toInt

      b match {
        case "+" => ice = ice + d
        case "-" => if (ice >= d) {ice = ice - d} else {children = children + 1}
      }
    }

    println(ice + " " + children)

  }
}


You are given $$$n$$$ points on the plane. The polygon formed from all the $$$n$$$ points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $$$1$$$ to $$$n$$$, in clockwise order.We define the distance between two points $$$p_1 = (x_1, y_1)$$$ and $$$p_2 = (x_2, y_2)$$$ as their Manhattan distance: $$$$$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$$$$Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as $$$p_1, p_2, \ldots, p_k$$$ $$$(k \geq 3)$$$, then the perimeter of the polygon is $$$d(p_1, p_2) + d(p_2, p_3) + \ldots + d(p_k, p_1)$$$.For some parameter $$$k$$$, let's consider all the polygons that can be formed from the given set of points, having any $$$k$$$ vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define $$$f(k)$$$ to be the maximal perimeter.Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:  In the middle polygon, the order of points ($$$p_1, p_3, p_2, p_4$$$) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is ($$$p_1, p_2, p_3, p_4$$$), which is the left polygon.Your task is to compute $$$f(3), f(4), \ldots, f(n)$$$. In other words, find the maximum possible perimeter for each possible number of points (i.e. $$$3$$$ to $$$n$$$).

The first line contains a single integer $$$n$$$ ($$$3 \leq n \leq 3\cdot 10^5$$$) — the number of points.  Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^8 \leq x_i, y_i \leq 10^8$$$) — the coordinates of point $$$p_i$$$. The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.

NoteIn the first example, for $$$f(3)$$$, we consider four possible polygons:   ($$$p_1, p_2, p_3$$$), with perimeter $$$12$$$.  ($$$p_1, p_2, p_4$$$), with perimeter $$$8$$$.  ($$$p_1, p_3, p_4$$$), with perimeter $$$12$$$.  ($$$p_2, p_3, p_4$$$), with perimeter $$$12$$$. For $$$f(4)$$$, there is only one option, taking all the given points. Its perimeter $$$14$$$.In the second example, there is only one possible polygon. Its perimeter is $$$8$$$.

object E extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }

  case class P(x: Long, y: Long)

  def dist(p1: P, p2: P): Long = {
    Math.abs(p2.x - p1.x) + Math.abs(p1.y - p2.y)
  }

  val Array(n) = readInts(1)

  val ps = Array.fill(n) {
    val Array(x, y) = readLongs(2)
    P(x, y)
  }

  val psByX = ps.sortBy(_.x)
  val psByY = ps.sortBy(_.y)

  var on3 = 0L

  def triangle(p1: P, p2: P, p3: P): Long = {
    dist(p1, p2) + dist(p2, p3) + dist(p3, p1)
  }

  for (p <- ps) {
    val d1 = triangle(psByX.head, psByY.last, p)
    val d2 = triangle(psByX.head, psByY.head, p)
    val d3 = triangle(psByX.last, psByY.last, p)
    val d4 = triangle(psByX.last, psByY.head, p)
    val d = d1 max d2 max d3 max d4
    if (d > on3) on3 = d
  }

  val res = Array.ofDim[Long](n - 2)
  res(0) = on3

  val on4 = 2 * (psByX.last.x - psByX.head.x + psByY.last.y - psByY.head.y)

  for (i <- 1 until res.length) res(i) = on4

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}

import java.io._
import java.util
import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  case class Point(x: Int, y: Int)

  @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    var mxX = -1000000000
    var mnX = 1000000000
    var mxY = -1000000000
    var mnY = 1000000000
    val arr = Array.fill(n) {
      val p = Point(in.nextInt, in.nextInt)
      mxX = math.max(mxX, p.x)
      mnX = math.min(mnX, p.x)
      mxY = math.max(mxY, p.y)
      mnY = math.min(mnY, p.y)
      p
    }

    var ans3 = 0
    arr.foreach { p =>
      ans3 = math.max(ans3, dist(p.x, mxX, p.y, mxY))
      ans3 = math.max(ans3, dist(p.x, mxX, p.y, mnY))
      ans3 = math.max(ans3, dist(p.x, mnX, p.y, mxY))
      ans3 = math.max(ans3, dist(p.x, mnX, p.y, mnY))
    }

    val ans4 = (mxX - mnX) * 2 + (mxY - mnY) * 2

    print(ans3 + (" " + ans4) * (n - 3))

  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

import java.util

import scala.collection.mutable

object E extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  case class P(x: Long, y: Long)

  def dist(x1: Long, y1: Long, x2: Long, y2: Long): Long = {
    Math.abs(x2 - x1) + Math.abs(y2 - y1)
  }

  val Array(n) = readInts(1)
  val psBuilder = new mutable.ArrayBuilder.ofRef[P]

  for (_ <- 0 until n) {
    val Array(x, y) = readLongs(2)
    psBuilder += P(x, y)
  }

  val ps = psBuilder.result()
  val psByX = ps.sortBy(_.x)
  val psByY = ps.sortBy(_.y)

  var on3ByX, on3ByY = 0L

  {
    val first = psByX.head
    val last = psByX.last
    for (i <- 1 until n - 1) {
      val p = psByX(i)
      val d = dist(first.x, first.y, p.x, p.y) + dist(p.x, p.y, last.x, last.y) + dist(first.x, first.y, last.x, last.y)
      if (d > on3ByX) on3ByX = d
    }
  }

  {
    val first = psByY.head
    val last = psByY.last
    for (i <- 1 until n - 1) {
      val p = psByY(i)
      val d = dist(first.x, first.y, p.x, p.y) + dist(p.x, p.y, last.x, last.y) + dist(first.x, first.y, last.x, last.y)
      if (d > on3ByY) on3ByY = d
    }
  }

  val res = Array.ofDim[Long](n - 2)
  res(0) = Math.max(on3ByX, on3ByY)

  val on4 = 2 * (psByX.last.x - psByX.head.x + psByY.last.y - psByY.head.y)

  for (i <- 1 until res.length) res(i) = on4

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}

import java.util

import scala.collection.mutable

object E extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  case class P(x: Int, y: Int)

  def dist(x1: Int, y1: Int, x2: Int, y2: Int): Long = {
    Math.abs(x2 - x1) + Math.abs(y2 - y1)
  }

  val Array(n) = readInts(1)
  val psBuilder = new mutable.ArrayBuilder.ofRef[P]

  for (i <- 0 until n) {
    val Array(x, y) = readInts(2)
    psBuilder += P(x, y)
  }

  val ps = psBuilder.result
  val psByX = ps.sortBy(_.x)
  val psByY = ps.sortBy(_.y)

  var on3ByX = 0L

  {
    val first = psByX.head
    val last = psByX.last
    for (i <- 1 until n - 1) {
      val p = psByX(i)
      val d = dist(first.x, first.y, p.x, p.y) + dist(p.x, p.y, last.x, last.y ) + dist(first.x, first.y, last.x, last.y)
      if (d > on3ByX) on3ByX = d
    }
  }

  var on3ByY = 0L

  {
    val first = psByY.head
    val last = psByY.last
    for (i <- 1 until n - 1) {
      val p = psByY(i)
      val d = dist(first.x, first.y, p.x, p.y) + dist(p.x, p.y, last.x, last.y ) + dist(first.x, first.y, last.x, last.y)
      if (d > on3ByY) on3ByY = d
    }
  }

  val res = Array.ofDim[Long](n - 2)
  res(0) = on3ByX max on3ByY

  val on4 = 2 * (psByX.last.x - psByX.head.x + psByY.last.y - psByY.head.y)

  for (i <- 1 until res.length) res(i) = on4

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString(" "))

  Console.flush
}

import java.io._
import java.util
import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  case class Point(x: Int, y: Int)

  def dist(p1: Point, p2: Point): Long = math.abs(p1.x - p2.x) + math.abs(p1.y - p2.y)

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val arr = Array.fill(n)(Point(in.nextInt, in.nextInt))
    val mxX: Long = arr.maxBy(_.x).x
    val mnX: Long = arr.minBy(_.x).x
    val mxY: Long = arr.maxBy(_.y).y
    val mnY: Long = arr.minBy(_.y).y

    val t = ArrayBuffer[Point]()
    arr.foreach { p =>
      if (p.x == mxX || p.x == mnX || p.y == mxY || p.y == mnY)
        t.append(p)
    }

    val ans3 = (for {
      p1 <- t
      p2 <- t
      p3 <- t
    } yield dist(p1, p2) + dist(p2, p3) + dist(p3, p1)).max

    val ans4 = (mxX - mnX) * 2 + (mxY - mnY) * 2

    print(ans3 + (" " + ans4) * (n - 3))

  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}


Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains $$$n$$$ rows of seats and there are $$$m$$$ seats in each row. Then the classroom can be represented as an $$$n \times m$$$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $$$k$$$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.

The first line contains three positive integers $$$n,m,k$$$ ($$$1 \leq n, m, k \leq 2\,000$$$), where $$$n,m$$$ represent the sizes of the classroom and $$$k$$$ is the number of consecutive seats you need to find. Each of the next $$$n$$$ lines contains $$$m$$$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.

A single number, denoting the number of ways to find $$$k$$$ empty seats in the same row or column.

NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement.   $$$(1,3)$$$, $$$(2,3)$$$  $$$(2,2)$$$, $$$(2,3)$$$  $$$(2,1)$$$, $$$(2,2)$$$

import java.io._
import java.util.StringTokenizer

import scala.annotation.tailrec

/**
  * Created by amir.
  */

object A extends App {

  class RW(val inputFile: String, val outputFile: String) {
    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var out = new PrintWriter(new OutputStreamWriter(System.out))

    /* val f = new File(inputFile)
    if (f.exists && f.canRead)
    try {
    br = new BufferedReader(new FileReader(f))
    out = new PrintWriter(new FileWriter(outputFile))
    } catch {
    case e: IOException =>
    e.printStackTrace()
    }*/

    private var st: StringTokenizer = _
    var eof = false

    def nextLine: String = {
      var s = ""
      try
        s = br.readLine()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      s
    }

    def next: String = {
      while (st == null || !st.hasMoreTokens)
        try
          st = new StringTokenizer(br.readLine)
        catch {
          case _: IOException =>
            eof = true
            ""
        }
      st.nextToken
    }

    def nextLong: Long = next.toLong

    def nextInt: Int = next.toInt

    def println(): Unit = out.println()

    def println(o: Any): Unit = out.println(o)

    def print(o: Any): Unit = out.print(o)

    def close(): Unit = {
      try {
        br.close()
      } catch {
        case e: IOException =>
          e.printStackTrace()
      }

      out.close()
    }
  }

  override def main(args: Array[String]) {
    val rw = new RW("input.txt", "output.txt")

    def count(s: IndexedSeq[Char], k: Int): Int = {
      @tailrec def count(cur: Int, i: Int, curSum: Int): Int =
      if (i >= s.length ) curSum
      else if (s(i) == '*') count(0, i + 1, curSum)
      else count(cur + 1, i + 1, curSum + (if (cur + 1 >= k) 1 else 0))
      count(0, 0, 0)
    }

    val n, m, k = rw.nextInt
    val cl = for (_ <- 1 to n) yield rw.next

    rw.print(cl.map(s => count(s, k)).sum + (if (k == 1) 0 else cl.transpose.map(s => count(s, k)).sum))
    rw.close()
  }
}

import java.io._
import java.util.StringTokenizer

import scala.annotation.tailrec

/**
  * Created by amir.
  */

object A extends App {

  class RW(val inputFile: String, val outputFile: String) {
    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var out = new PrintWriter(new OutputStreamWriter(System.out))

    /* val f = new File(inputFile)
    if (f.exists && f.canRead)
    try {
    br = new BufferedReader(new FileReader(f))
    out = new PrintWriter(new FileWriter(outputFile))
    } catch {
    case e: IOException =>
    e.printStackTrace()
    }*/

    private var st: StringTokenizer = _
    var eof = false

    def nextLine: String = {
      var s = ""
      try
        s = br.readLine()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      s
    }

    def next: String = {
      while (st == null || !st.hasMoreTokens)
        try
          st = new StringTokenizer(br.readLine)
        catch {
          case _: IOException =>
            eof = true
            ""
        }
      st.nextToken
    }

    def nextLong: Long = next.toLong

    def nextInt: Int = next.toInt

    def println(): Unit = out.println()

    def println(o: Any): Unit = out.println(o)

    def print(o: Any): Unit = out.print(o)

    def close(): Unit = {
      try {
        br.close()
      } catch {
        case e: IOException =>
          e.printStackTrace()
      }

      out.close()
    }
  }

  override def main(args: Array[String]) {
    val rw = new RW("input.txt", "output.txt")

    def count(s: IndexedSeq[Char], k: Int): Int = {
      @tailrec def count(cur: Int, i: Int, curSum: Int): Int =
        if (i >= s.length) curSum
        else if (s(i) == '*') count(0, i + 1, curSum)
        else count(cur + 1, i + 1, curSum + (if (cur + 1 >= k) 1 else 0))

      count(0, 0, 0)
    }

    val n, _, k = rw.nextInt
    val cl = for (_ <- 1 to n) yield rw.next

    rw.print(cl.map(s => count(s, k)).sum + (if (k == 1) 0 else cl.transpose.map(s => count(s, k)).sum))
    rw.close()
  }
}

import java.io._
import java.util.StringTokenizer

import scala.annotation.tailrec

/**
  * Created by amir.
  */

object A extends App {

  class RW(val inputFile: String, val outputFile: String) {
    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var out = new PrintWriter(new OutputStreamWriter(System.out))

    /* val f = new File(inputFile)
    if (f.exists && f.canRead)
    try {
    br = new BufferedReader(new FileReader(f))
    out = new PrintWriter(new FileWriter(outputFile))
    } catch {
    case e: IOException =>
    e.printStackTrace()
    }*/

    private var st: StringTokenizer = _
    var eof = false

    def nextLine: String = {
      var s = ""
      try
        s = br.readLine()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      s
    }

    def next: String = {
      while (st == null || !st.hasMoreTokens)
        try
          st = new StringTokenizer(br.readLine)
        catch {
          case _: IOException =>
            eof = true
            ""
        }
      st.nextToken
    }

    def nextLong: Long = next.toLong

    def nextInt: Int = next.toInt

    def println(): Unit = out.println()

    def println(o: Any): Unit = out.println(o)

    def print(o: Any): Unit = out.print(o)

    def close(): Unit = {
      try {
        br.close()
      } catch {
        case e: IOException =>
          e.printStackTrace()
      }

      out.close()
    }
  }

  override def main(args: Array[String]) {
    val rw = new RW("input.txt", "output.txt")

    def count(s: IndexedSeq[Char], k: Int): Int = {
      def count(cur: Int, i: Int): Int =
      if (i >= s.length ) 0
      else if (s(i) == '*') count(0, i + 1)
      else count(cur + 1, i + 1) + (if (cur + 1 >= k) 1 else 0)
      count(0, 0)
    }

    val n, m, k = rw.nextInt
    val cl = for (_ <- 1 to n) yield rw.next

    rw.print(cl.map(s => count(s, k)).sum + cl.transpose.map(s => count(s, k)).sum)
    rw.close()
  }
}

import java.io._
import java.util.StringTokenizer

import scala.annotation.tailrec

/**
  * Created by amir.
  */

object A extends App {

  class RW(val inputFile: String, val outputFile: String) {
    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var out = new PrintWriter(new OutputStreamWriter(System.out))

    /* val f = new File(inputFile)
    if (f.exists && f.canRead)
    try {
    br = new BufferedReader(new FileReader(f))
    out = new PrintWriter(new FileWriter(outputFile))
    } catch {
    case e: IOException =>
    e.printStackTrace()
    }*/

    private var st: StringTokenizer = _
    var eof = false

    def nextLine: String = {
      var s = ""
      try
        s = br.readLine()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      s
    }

    def next: String = {
      while (st == null || !st.hasMoreTokens)
        try
          st = new StringTokenizer(br.readLine)
        catch {
          case _: IOException =>
            eof = true
            ""
        }
      st.nextToken
    }

    def nextLong: Long = next.toLong

    def nextInt: Int = next.toInt

    def println(): Unit = out.println()

    def println(o: Any): Unit = out.println(o)

    def print(o: Any): Unit = out.print(o)

    def close(): Unit = {
      try {
        br.close()
      } catch {
        case e: IOException =>
          e.printStackTrace()
      }

      out.close()
    }
  }

  override def main(args: Array[String]) {
    val rw = new RW("input.txt", "output.txt")

    def count(s: IndexedSeq[Char], k: Int): Int = {
      @tailrec def count(cur: Int, i: Int, curSum: Int): Int =
        if (i >= s.length) curSum
        else if (s(i) == '*') count(0, i + 1, curSum)
        else count(cur + 1, i + 1, curSum + (if (cur + 1 >= k) 1 else 0))

      count(0, 0, 0)
    }

    val n, _, k = rw.nextInt
    val cl = for (_ <- 1 to n) yield rw.next

    def f[T <: IndexedSeq[String]]: T => Int = _.map(s => count(s, k)).sum

    rw.print(f(cl) + (if (k == 1) 0 else f(cl.transpose.map(_.toString))))
    rw.close()
  }
}


There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i, j) (i < j) exists such that  or , where  denotes intersection of sets, and  denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup.

If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower).

NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below.  For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column.

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val grid = Array.fill(n){ readLine.toCharArray.map(_ == '#' )}
  val counts = Array.fill(n, m){ 0 }

  var ok = true
  var usedRow, usedCol = new mutable.BitSet

  for {
    r0 <- 0 until n
    c0 <- 0 until m
    if grid(r0)(c0) && counts(r0)(c0) == 0
  } {
    val rows, cols = ArrayBuffer.empty[Int]
    for (c <- 0 until m) {
      if (grid(r0)(c)) {
        cols += c
        if (usedCol(c)) ok = false
        usedCol += c
      }
    }
    for (r <- 0 until n) {
      if (grid(r)(c0)) {
        rows += r
        if (usedRow(r)) ok = false
        usedRow += r
      }
    }
    for {
      r <- rows
      c <- cols
    } {
      if (!grid(r)(c)) ok = false
      counts(r)(c) += 1
      //grid(r)(c) = false
    }
  }

  //counts.foreach(c => println(c.mkString))

  if (counts.exists(_.exists(_ > 1))) ok = false

  println(if (ok) "Yes" else "No")
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val grid = Array.fill(n){ readLine.toCharArray.map(_ == '#' )}
  val counts = Array.fill(n, m){ 0 }

  var ok = true
  var usedRow, usedCol = new mutable.BitSet

  for {
    r0 <- 0 until n
    c0 <- 0 until m
    if grid(r0)(c0) && counts(r0)(c0) == 0
  } {
    val rows, cols = ArrayBuffer.empty[Int]
    for (c <- 0 until m) {
      if (grid(r0)(c)) {
        cols += c
        //if (usedCol(c)) ok = false
        usedCol += c
      }
    }
    for (r <- 0 until n) {
      if (grid(r)(c0)) {
        rows += r
        //if (usedRow(r)) ok = false
        usedRow += r
      }
    }
    for {
      r <- rows
      c <- cols
    } {
      if (!grid(r)(c)) ok = false
      counts(r)(c) += 1
      //grid(r)(c) = false
    }
  }

  //counts.foreach(c => println(c.mkString))

  if (counts.exists(_.exists(_ > 1))) ok = false

  println(if (ok) "Yes" else "No")
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val grid = Array.fill(n){ readLine.toCharArray.map(_ == '#' )}
  val counts = Array.fill(n, m){ 0 }

  var ok = true
  var usedRow, usedCol = new mutable.BitSet

  for {
    r0 <- 0 until n
    c0 <- 0 until m
    if grid(r0)(c0) && counts(r0)(c0) == 0
  } {
    val rows = ArrayBuffer(r0)
    val cols = ArrayBuffer(c0)
    for (c <- c0 + 1 until m) {
      if (grid(r0)(c)) {
        cols += c
        //if (usedCol(c)) ok = false
        usedCol += c
      }
    }
    for (r <- r0 + 1 until n) {
      if (grid(r)(c0)) {
        rows += r
        //if (usedRow(r)) ok = false
        usedRow += r
      }
    }
    for {
      r <- rows
      c <- cols
    } {
      if (!grid(r)(c)) ok = false
      counts(r)(c) += 1
      //grid(r)(c) = false
    }
  }

  //counts.foreach(c => println(c.mkString))

  if (counts.exists(_.exists(_ > 1))) ok = false

  println(if (ok) "Yes" else "No")
}


You're given an undirected graph with $$$n$$$ nodes and $$$m$$$ edges. Nodes are numbered from $$$1$$$ to $$$n$$$.The graph is considered harmonious if and only if the following property holds:  For every triple of integers $$$(l, m, r)$$$ such that $$$1 \le l < m < r \le n$$$, if there exists a path going from node $$$l$$$ to node $$$r$$$, then there exists a path going from node $$$l$$$ to node $$$m$$$. In other words, in a harmonious graph, if from a node $$$l$$$ we can reach a node $$$r$$$ through edges ($$$l < r$$$), then we should able to reach nodes $$$(l+1), (l+2), \ldots, (r-1)$$$ too.What is the minimum number of edges we need to add to make the graph harmonious?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 200\ 000$$$ and $$$1 \le m \le 200\ 000$$$). The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \neq v_i$$$), that mean that there's an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).

Print the minimum number of edges we have to add to the graph to make it harmonious.

NoteIn the first example, the given graph is not harmonious (for instance, $$$1 < 6 < 7$$$, node $$$1$$$ can reach node $$$7$$$ through the path $$$1 \rightarrow 2 \rightarrow 7$$$, but node $$$1$$$ can't reach node $$$6$$$). However adding the edge $$$(2, 4)$$$ is sufficient to make it harmonious.In the second example, the given graph is already harmonious.

import scala.collection.mutable

object D {
  import InOut._
  def main(args: Array[String]): Unit = {}

  final class UnionFind(size: Int) {

    private val height = Array.fill(size){ 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

  val n, m = nextInt
  val adjBuilders = Array.fill(n)(new mutable.ArrayBuilder.ofInt)

  for (_ <- 1 to m) {
    val _u, _v = nextInt
    val u = Math.min(_u, _v) - 1
    val v = Math.max(_u, _v) - 1
    adjBuilders(u) += v
  }
  val adjs = adjBuilders.map(_.result())
  val con = new UnionFind(n)
  var res = 0L

  var u = 0
  while (u < n) {
    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      con.union(u, v)
      i += 1
    }
    u += 1
  }

  val max = Array.tabulate(n)(identity)

  var i = 0
  while (i < n) {
    val f = con.find(i)
    if (i > max(f)) max(f) = i
    i += 1
  }

  var l = 0
  while (l < n) {
    val l0 = l
    var r = max(con.find(l0))
    while (l < r) {
      l += 1
      if (!con.same(l0, l)) {
        val max2 = max(con.find(l))
        if (max2 > r) r = max2
        con.union(l0, l)
        res += 1
      }
    }
    l += 1
  }

  out.println(res)
  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}