We call two numbers $$$x$$$ and $$$y$$$ similar if they have the same parity (the same remainder when divided by $$$2$$$), or if $$$|x-y|=1$$$. For example, in each of the pairs $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$, the numbers are similar to each other, and in the pairs $$$(1, 4)$$$, $$$(3, 12)$$$, they are not.You are given an array $$$a$$$ of $$$n$$$ ($$$n$$$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array $$$a = [11, 14, 16, 12]$$$, there is a partition into pairs $$$(11, 12)$$$ and $$$(14, 16)$$$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — length of array $$$a$$$. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$).

For each test case print:   YES if the such a partition exists,  NO otherwise.  The letters in the words YES and NO can be displayed in any case.

NoteThe first test case was explained in the statement.In the second test case, the two given numbers are not similar.In the third test case, any partition is suitable.

import scala.io.StdIn.readLine

object C {

  def solution(s: Seq[Int]): String = {
    val (ev, odd) = s.partition(_ % 2 == 0)
    val (ss, sb) = if (ev.size < odd.size) (ev, odd) else (odd, ev)
    if ((ss.length % 2 == 0) || {
      val other = sb.toSet
      ss.exists { se =>
        other.contains(se - 1) || other.contains(se + 1)
      }
    }) "YES" else "NO"
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val _ = readLine.toInt
      val s = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(s))
    }
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CF644(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class CF644(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val a = na(n)
      var cno = 0
      var cne = 0

      REP(n) { i =>
        if(a(i) % 2 == 0) cne += 1
        else cno += 1
      }

      if(cne % 2 == 0 && cno % 2 == 0) {
        out.println("YES")
      } else {
        scala.util.Sorting.quickSort(a)
        var yes = false
        REP(n-1, 1) { i =>
          if(a(i) - a(i-1) == 1) yes = true
        }
        if(yes) {
          out.println("YES")
        } else out.println("NO")
      }
    }
  }
}

object C extends App {
  private def closest(an: List[Int], bn: List[Int]): Boolean = {
    def go(an: List[Int], bn: List[Int]): Boolean =
      if (an.isEmpty || bn.isEmpty) false
      else {
        val am = an.drop(an.lastIndexWhere(_ < bn.head))
        val bl = bn.drop(bn.lastIndexWhere(_ < an.head))

        val (a, b) = (am.head, bl.head)
        val (m, l) = (am.length, bl.length)

        val d = (a - b).abs

        if (d == 1) true
        else if (a < b) go(am.tail, bl)
        else if (a > b) go(am, bl.tail)
        else if (m < l) go(am, bl.tail)
        else go(am.tail, bl)
      }

    go(an, bn)
  }

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

    val (al, ar) = an.partition(_ % 2 == 0)

    if (al.length % 2 == 0) println("YES")
    else {
      val (bl, br) = (al.sorted, ar.sorted)

      if (closest(bl, br)) println("YES")
      else println("NO")
    }
  }
}

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

    val (al, ar) = an.partition(_ % 2 == 0)

    val ans = al.length % 2 == 0 || al.exists(l => ar.exists(r => 1 == (l - r).abs))

    if (ans) println("YES")
    else println("NO")
  }
}

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val (al, ar) = an.partition(_ % 2 == 0)

    if (al.length % 2 == 0) println("YES")
    else {
      val (bl, br) = (al.sorted, ar.sorted)

      var i = 0
      var j = 0
      var d = 200

      while (d != 1 && i < bl.length && j < br.length) {
        val (l, r) = (bl(i), br(j))

        i = if (l < r) bl.lastIndexWhere(_ < r) else i
        j = if (r < l) br.lastIndexWhere(_ < l) else j

        d = d min (bl(i) - br(j)).abs

        if (l < r) j += 1
        else if (r < l) i += 1
        else if (i + 1 < bl.length) i += 1
        else j += 1
      }

      if (d == 1) println("YES")
      else println("NO")
    }
  }
}


You are given an angle $$$\text{ang}$$$. The Jury asks You to find such regular $$$n$$$-gon (regular polygon with $$$n$$$ vertices) that it has three vertices $$$a$$$, $$$b$$$ and $$$c$$$ (they can be non-consecutive) with $$$\angle{abc} = \text{ang}$$$ or report that there is no such $$$n$$$-gon.  If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $$$998244353$$$.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 180$$$) — the number of queries.  Each of the next $$$T$$$ lines contains one integer $$$\text{ang}$$$ ($$$1 \le \text{ang} < 180$$$) — the angle measured in degrees.

For each query print single integer $$$n$$$ ($$$3 \le n \le 998244353$$$) — minimal possible number of vertices in the regular $$$n$$$-gon or $$$-1$$$ if there is no such $$$n$$$.

NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular $$$18$$$-gon. For example, $$$\angle{v_2 v_1 v_6} = 50^{\circ}$$$.The example angle for the third query is $$$\angle{v_{11} v_{10} v_{12}} = 2^{\circ}$$$.In the fourth query, minimal possible $$$n$$$ is $$$180$$$ (not $$$90$$$).

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

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

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

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

  def solve(): Unit = {
    val ans = Array.fill[Int](181)(-1)
    3 to 360 foreach { n =>
      REP(n - 2, 1) { cnt =>
        if (cnt * 180 % n == 0) {
          val angle = cnt * 180 / n
          if (ans(angle) == -1) ans(angle) = n
        }
      }
    }

//    debug(ans)

    REP(ni()) { _ =>
      val angle = ni()
      out.println(ans(angle))
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val ans = Array.fill[Int](181)(-1)
    3 to 180 foreach { n =>
      if (180 % n == 0) {
        val unit = 180 / n
        REP(n - 2, 1) { cnt =>
          val angle = cnt * unit
          if (ans(angle) == -1) ans(angle) = n
        }
      }
    }

    ans(179) = 360
//    debug(ans)

    REP(ni()) { _ =>
      val angle = ni()
      out.println(ans(angle))
    }
  }

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

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

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

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

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

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

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

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


After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i,  j,  k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!

The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.

Print one number — the quantity of triples (i,  j,  k) such that i,  j and k are pairwise distinct and ai·aj·ak is minimum possible.

NoteIn the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.

import scala.io.StdIn._

object SolutionB extends App {
  readLine()
  def readInts() = readLine() split " " map (_.toInt) toSeq;

  val a = readInts()
  val min3 = a.sorted.take(3)

  def newtonBinom(n: Long, k: Long): Long = (n - k + 1 to n).product / (1.toLong to k).product

  println(
    min3 groupBy(x => x) mapValues (_.length.toLong) map { case (x, n) =>
        newtonBinom(a.count(_ == x) , Math.min(n, 3))
    } product
  )
}

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

object test
{
	def main(args: Array[String]) =
	{
		val s = new Scanner(System.in)
		val n = s.nextInt
		var lst = new Array[Int](n)

		for(i<-0 until n) lst(i) = s.nextInt
		lst = lst.sorted

		var top3 = new Array[BigInt](3)
		var v = lst(0)+1
		var j = -1
		var break = false
		for(i<-0 until n if break==false)
		{
			if(lst(i)==v)
			{
				top3(j)+=1
			}
			else
			{
				j+=1
				if(j>=3)
				{
					break=true
				}
				else
				{
					top3(j)=1
					v=lst(i)
				}
			}
		}
		//println(top3(0),top3(1),top3(2))
		if(top3(0)>=3)
		{
			// C(top(0),3)
			val n=top3(0)
			println(n*(n-1)*(n-2)/6)
		}
		else if(top3(0)+top3(1)>=3)
		{
			// C(top(1),3-top(0))
			val n=top3(1)
			if(3-top3(0)==2)
				println(n*(n-1)/2)
			else
				println(n)
		}
		else
		{
			println(top3(2))
		}
	}
}

import scala.io.StdIn._

object Solution extends App {
  readLine()
  def readInts() = readLine() split " " map (_.toInt) toSeq;

  val a = readInts()
  val min3 = a.sorted.take(3)

  println(
    min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) => (n+1) to Math.max(n+3, a.count(_ == x)) } product
  )

}

import scala.io.StdIn._

object SolutionB extends App {
  readLine()
  def readInts() = readLine() split " " map (_.toInt) toSeq;

  val a = readInts()
  val min3 = a.sorted.take(3)

  println(
    min3 groupBy(x => x) mapValues (_.length.toLong) map { case (x, n) =>
        val rng = (n+1).toLong to a.count(_ == x)
        val rngSize = rng.size.toLong
        rng.product / (Math.max(1, rngSize) to rngSize).product
    } product
  )
}

import scala.io.StdIn._

object SolutionB extends App {
  readLine()
  def readInts() = readLine() split " " map (_.toInt) toSeq;

  val a = readInts()
  val min3 = a.sorted.take(3)

  println(
    min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) => (n+1) to Math.min(n+3, a.count(_ == x)) } product
  )

}

import scala.io.StdIn._

object SolutionB extends App {
  readLine()
  def readInts() = readLine() split " " map (_.toInt) toSeq;

  val a = readInts()
  val min3 = a.sorted.take(3)

  println(
    min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) => (n+1) to a.count(_ == x) } product
  )
}

import scala.io.StdIn._

object SolutionB extends App {
  readLine()
  def readInts() = readLine() split " " map (_.toInt) toSeq;

  val a = readInts()
  val min3 = a.sorted.take(3)

  println(
    min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) =>
      val cnt = a.count(_ == x)
      Math.max(n+1, cnt-2) to cnt
    } product
  )

}

import scala.io.StdIn._

object Solution extends App {
  readLine()
  def readInts() = readLine() split " " map (_.toInt) toSeq;

  val a = readInts()
  val min3 = a.sorted.take(3)

  println(
    min3 groupBy(x => x) mapValues (_.length) flatMap { case (x, n) => (n+1) to a.count(_ == x) } product
  )
}

import scala.io.StdIn._

object B extends App {
  readLine()
  def readInts() = readLine() split " " map (_.toInt) toSeq

  val a = readInts()
  val min3 = a.sorted.take(3)

  println(
    min3 groupBy(x => x) mapValues (_.length.toLong) flatMap { case (x, n) => n to a.count(_ == x) } product
  )
}

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

object test
{
	def main(args: Array[String]) =
	{
		val s = new Scanner(System.in)
		val n = s.nextInt
		var lst = new Array[Int](n)

		for(i<-0 until n) lst(i) = s.nextInt
		lst = lst.sorted

		var top3 = new Array[BigInt](3)
		var v = lst(0)+1
		var j = -1
		var break = false
		for(i<-0 until n if break==false)
		{
			if(lst(i)==v)
			{
				top3(j)+=1
			}
			else
			{
				j+=1
				if(j>=3)
				{
					break=true
				}
				else
				{
					top3(j)=1
					v=lst(i)
				}
			}
		}
		println(top3(0),top3(1),top3(2))
		if(top3(0)>=3)
		{
			// C(top(0),3)
			val n=top3(0)
			println(n*(n-1)*(n-2)/6)
		}
		else if(top3(0)+top3(1)>=3)
		{
			// C(top(1),3-top(0))
			val n=top3(1)
			if(3-top3(0)==2)
				println(n*(n-1)/2)
			else
				println(n)
		}
		else
		{
			println(top3(2))
		}
	}
}

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

object test
{
	def main(args: Array[String]) =
	{
		val s = new Scanner(System.in)
		val n = s.nextInt
		var lst = new Array[Int](n)

		for(i<-0 until n) lst(i) = s.nextInt
		lst = lst.sorted

		var top3 = new Array[Int](3)
		var v = lst(0)+1
		var j = -1
		var break = false
		for(i<-0 until n if break==false)
		{
			if(lst(i)==v)
			{
				top3(j)+=1
			}
			else
			{
				j+=1
				if(j>=3)
				{
					break=true
				}
				else
				{
					top3(j)=1
					v=lst(i)
				}
			}
		}
		if(top3(0)>=3)
		{
			// C(top(0),3)
			val n=top3(0)
			println(n*(n-1)*(n-2)/6)
		}
		else if(top3(0)+top3(1)>=3)
		{
			// C(top(1),3-top(0))
			val n=top3(1)
			if(3-top3(0)==2)
				println(n*(n-1)/2)
			else
				println(n)
		}
		else
		{
			println(top3(2))
		}
	}
}

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

object test
{
	def main(args: Array[String]) =
	{
		val s = new Scanner(System.in)
		val n = s.nextInt
		var lst = new Array[Int](n)

		for(i<-0 until n) lst(i) = s.nextInt
		lst = lst.sorted

		var top3 = new Array[Int](3)
		var v = lst(0)+1
		var j = -1
		var break = false
		for(i<-0 until n if break==false)
		{
			if(lst(i)==v)
			{
				top3(j)+=1
			}
			else
			{
				j+=1
				if(j>=3)
				{
					break=true
				}
				else
				{
					top3(j)=1
					v=lst(i)
				}
			}
		}
		if(top3(0)>=3)
		{
			// C(top(0),3)
			val n=top3(0)
			println(n*(n-1)*(n-2))
		}
		else if(top3(0)+top3(1)>=3)
		{
			// C(top(1),3-top(0))
			val n=top3(1)
			if(3-top3(0)==2)
				println(n*(n-1))
			else
				println(n)
		}
		else
		{
			println(top3(2))
		}
	}
}


You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes.

The first line contains two integers n and k (1 ≤ k ≤ n ≤  105) — the size of the array a and the number of subsegments you have to split the array to. The second line contains n integers a1,  a2,  ...,  an ( - 109  ≤  ai ≤  109).

Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.

NoteA subsegment [l,  r] (l ≤ r) of array a is the sequence al,  al + 1,  ...,  ar.Splitting of array a of n elements into k subsegments [l1, r1], [l2, r2], ..., [lk, rk] (l1 = 1, rk = n, li = ri - 1 + 1 for all i > 1) is k sequences (al1, ..., ar1), ..., (alk, ..., ark).In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result.In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is min( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5.

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, k) = readInts(2)
  val as = readInts(n)

  val res = if (k == 1) as.min
  else if (k > 2) as.max
  else as.last max as.head

  println(res)

  Console.flush
}


You are given three strings $$$s$$$, $$$t$$$ and $$$p$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose any character from $$$p$$$, erase it from $$$p$$$ and insert it into string $$$s$$$ (you may insert this character anywhere you want: in the beginning of $$$s$$$, in the end or between any two consecutive characters). For example, if $$$p$$$ is aba, and $$$s$$$ is de, then the following outcomes are possible (the character we erase from $$$p$$$ and insert into $$$s$$$ is highlighted):  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ ade;  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ dae;  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ dea;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ bde;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ dbe;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ deb;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ ade;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ dae;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ dea; Your goal is to perform several (maybe zero) operations so that $$$s$$$ becomes equal to $$$t$$$. Please determine whether it is possible.Note that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is represented by three consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \le |s| \le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \le |t| \le 100$$$) consisting of lowercase Latin letters. The third line of each query contains the string $$$p$$$ ($$$1 \le |p| \le 100$$$) consisting of lowercase Latin letters.

For each query print YES if it is possible to make $$$s$$$ equal to $$$t$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

4
ab
acxb
cax
a
aaaa
aaabbcc
a
aaaa
aabbcc
ab
baaa
aaaaa

NoteIn the first test case there is the following sequence of operation:   $$$s = $$$ ab, $$$t = $$$ acxb, $$$p = $$$ cax;  $$$s = $$$ acb, $$$t = $$$ acxb, $$$p = $$$ ax;  $$$s = $$$ acxb, $$$t = $$$ acxb, $$$p = $$$ a. In the second test case there is the following sequence of operation:   $$$s = $$$ a, $$$t = $$$ aaaa, $$$p = $$$ aaabbcc;  $$$s = $$$ aa, $$$t = $$$ aaaa, $$$p = $$$ aabbcc;  $$$s = $$$ aaa, $$$t = $$$ aaaa, $$$p = $$$ abbcc;  $$$s = $$$ aaaa, $$$t = $$$ aaaa, $$$p = $$$ bbcc.

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

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

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

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

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

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

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val s, t, p = ns()
      var i = 0
      var j = -1
      val flg = Array.ofDim[Boolean](t.length)
      while(i < s.length) {
        j = t.indexOf(s(i), j + 1)
        if (j != -1) {
          flg(j) = true
          i += 1
        } else {
          i = s.length
        }
      }

      val cnt = Array.ofDim[Int](26)
      REP(p.length) { i =>
        cnt(p(i)-'a') += 1
      }

      debug(flg)
      debug(cnt)

      def existsAllMissing = {
        flg.zipWithIndex.filter(!_._1).map(_._2).foreach { i =>
          cnt(t(i)-'a') -= 1
        }
        cnt.forall(_ >= 0)
      }

      if (j != -1 && existsAllMissing) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    }
  }
}

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

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

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

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

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

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

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val s, t, p = ns()
      var i, j = 0
      val flg = Array.ofDim[Boolean](t.length)
      while(i < s.length && j != -1) {
        j = t.indexOf(s(i), j)
        if (j != -1) flg(j) = true
        i += 1
      }

      val cnt = Array.ofDim[Int](26)
      REP(p.length) { i =>
        cnt(p(i)-'a') += 1
      }

      debug(flg)
      debug(cnt)

      def existsAllMissing = {
        flg.zipWithIndex.filter(!_._1).map(_._2).foreach { i =>
          cnt(t(i)-'a') -= 1
        }
        cnt.forall(_ >= 0)
      }

      if (i != -1 && existsAllMissing) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    }
  }
}

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

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

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

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

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

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

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val s, t, p = ns()
      var i = 0
      var j = -1
      val flg = Array.ofDim[Boolean](t.length)
      while(i < s.length) {
        j = t.indexOf(s(i), j + 1)
        if (j != -1) {
          flg(j) = true
          i += 1
        } else {
          i = s.length
        }
      }

      val cnt = Array.ofDim[Int](26)
      REP(p.length) { i =>
        cnt(p(i)-'a') += 1
      }

      debug(flg)
      debug(cnt)

      def existsAllMissing = {
        flg.zipWithIndex.filter(!_._1).map(_._2).foreach { i =>
          cnt(t(i)-'a') -= 1
        }
        cnt.forall(_ >= 0)
      }

      if (i != -1 && existsAllMissing) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    }
  }
}


Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.

In the first line of the input, you are given a single integer n (1 ≤ n ≤ 100) — the length of the side of the cake. Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.

Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.

NoteIf we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:   (1, 2) and (1, 3)  (3, 1) and (3, 3)  Pieces that share the same column are:   (2, 1) and (3, 1)  (1, 3) and (3, 3)

import scala.io.Source

object CF343_A extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt

  val rows = new Array[Int](100)
  val cols = new Array[Int](100)

  for(r <- 0 to n-1) {
      val line = in.next()
      for(c <- 0 to n-1) {
         if(line.charAt(c) == 'C') {
           cols(c) += 1
           rows(r) += 1
         }

      }
  }

  var res = 0

  for(i <- 0 to n-1) {
    if(2 <= rows(i)) res += combination(rows(i), 2)
    if(2 <= cols(i)) res += combination(cols(i), 2)
  }

  println(res)

  def combination(n: Int, r: Int): Int = {
    if(r == 0)
      1
    else if(n == 0)
      0
    else {
      var res = 0
      res += combination(n-1, r)
      res += combination(n-1, r-1)
      res
    }
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val rows = Array.ofDim[Int](n)
  val res = (1 to n).foldLeft(0l) {
    case (acc, _) =>
      val str = in.next()
      val count = str.count(_ == 'C')
      str.indices.foreach{i => if (str(i) == 'C') rows(i) += 1}
      acc + count * (count - 1) / 2
  } + rows.foldLeft(0l){
    case(acc, count) => acc + count * (count - 1) / 2
  }
  println(res)

}

object A629 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(read)
    val row = Array.fill(n)(0)
    val col = Array.fill(n)(0)
    for(i <- 0 until n; j <- 0 until n) {
      if(in(i)(j) == 'C') {
        row(i) += 1
        col(j) += 1
      }
    }
    val res = (row++col).foldLeft(0L){case (sum, i) => sum + (i.toLong*(i.toLong-1))/2}
    println(res)
  }

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

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

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

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

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

}

/**
 * @author pvasilyev
 * @since 23 Apr 2016
 */
object Problem155 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val cake = Array.ofDim[Char](n, n)
  for (i <- 0 until n) {
    cake(i) = scala.io.StdIn.readLine().toCharArray
  }
  var answer = 0

  for (i <- 0 until n) {
    var inRow = 0
    for (j <- 0 until n) {
      if (cake(i)(j) == 'C') {
        inRow += 1
      }
    }
    if (inRow >= 2) {
      answer += inRow * (inRow - 1) / 2
    }
  }
  for (j <- 0 until n) {
    var inCol = 0
    for (i <- 0 until n) {
      if (cake(i)(j) == 'C') {
        inCol += 1
      }
    }
    if (inCol >= 2) {
      answer += inCol * (inCol - 1) / 2
    }
  }
  println(answer)
}

object A {
  def main(args: Array[String]) {
    var arr = Array.ofDim[Char](128,128)
    var cnt = -1
    var n = 0
    for (ln <- io.Source.stdin.getLines) {
        if (cnt == -1) {
	    n = ln.trim.toInt
	}
        else {
	   for ( i <- 0 until ln.trim.length) {
		arr(cnt)(i) = ln(i)
	   }
	}
	cnt = cnt + 1
    }
    var res = 0
    for ( i <- 0 until n){
        var C = 0
	for (j<- 0 until n){
	    if(arr(i)(j)=='C'){
		C = C + 1
	    }
	}
        res = res + C*(C-1)/2
    }
    for ( j <- 0 until n){
        var C = 0
	for (i<- 0 until n){
	    if(arr(i)(j)=='C'){
		C = C + 1
	    }
	}
        res = res + C*(C-1)/2
    }
    println(res)
  }
}

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

object _629A extends CodeForcesApp {
  override type Result = Int

  override def solve(read: InputReader) = {
    val n = read[Int]
    val (rows, cols) = (Array.ofDim[Int](n+1), Array.ofDim[Int](n+1))

    for {
      i <- 1 to n
      line = read[String]
      j <- 1 to n
      if line(j-1) == 'C'
    } {
      rows(i) += 1
      cols(j) += 1
    }

    def nc2(i: Int) = (i*(i-1))/2

    rows.map(nc2).sum + cols.map(nc2).sum
  }

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

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

object _629A extends CodeForcesApp {
  override type Result = Int

  override def solve(read: InputReader) = {
    val n = read[Int]
    val chocolates = for {
      i <- 0 until n
      line = read[String]
      j <- 0 until n if line(j) == 'C'
    } yield (i, j)

    var ans = 0
    for {
      ((x1, y1), i) <- chocolates.zipWithIndex
      (x2, y2) <- chocolates drop (i + 1) if x1 == x2 || y1 == y2
    } ans += 1
    ans
  }

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import scala.annotation.tailrec
import scala.collection.immutable.IndexedSeq
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _629A extends CodeForcesApp {
  override type Result = Int

  override def solve(read: InputReader) = {
    val n = read[Int]
    val chocolates: IndexedSeq[(Int, Int)] = for {
      i <- 1 to n
      line = read[String]
      j <- 1 to n
      if line(j-1) == 'C'
    } yield (i, j)

    var ans = 0
    for (i <- chocolates.indices) {
      val (a1, a2) = chocolates(i)
      for (j <- chocolates.indices drop (i+1)) {
        val (b1, b2) = chocolates(j)
        if (a1 == b1 || a2 == b2) ans += 1
      }
    }

    ans
  }

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import java.util.Scanner

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

    var cake = new Array[String](n)
    for(i <- 0 until n)
      cake(i) = sc.nextLine()

    //
    var ans = BigInt(0)

    for(i <- 0 until n){
      val s = cake(i)

      var cnt = 0
      for(e <- s)
        if(e == 'C')
          cnt += 1

      if(cnt >= 2)
        ans += (cnt * (cnt-1)) / 2
    }

    for(i <- 0 until n){
      var cnt = 0
      for(j <- 0 until n)
        if(cake(j)(i) == 'C')
          cnt += 1

      if(cnt >= 2)
        ans += (cnt * (cnt-1)) / 2
    }

    println(ans)
  }
}

/**
 * Created by aborisenko on 21.02.16.
 */

import io.StdIn._

object Main extends App {
  def a629 (){
    val n = readInt()
    var arr: Array[String] = new Array[String](n)

    for( i <- 0 to n-1)
      arr(i) = readLine()

    var arr1: Array[Long] = Array.fill[Long](n)(0)
    var arr2: Array[Long] = Array.fill[Long](n)(0)

    for( i <- 0 to n-1)
      for( j <- 0 to n-1) {
        arr1(i) += (if( arr(i)(j) == 'C') 1 else 0)
        arr2(j) += (if( arr(i)(j) == 'C') 1 else 0)
      }

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

    var sum: Long = 0

    for( i <- 0 to n-1) {
      sum = f(arr1(i)) + sum
      sum = f(arr2(i)) + sum
    }

    println(sum)
  }

  a629()
}

import java.util.ArrayList
import java.util.StringTokenizer
import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object A_343_A {
    var br = createBufferedReader(); var debugV = false

      //COMMENT ME !
    runTest(Test.sa2)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading --------------------------
    val n = readLine.int
    val arr = Array.fill(n,n)(0)
    for(i <- 0 until n) {
      val line = readLine.string
      for(j <- 0 until n) {
        arr(i)(j) = if (line(j) == '.') 0 else 1
      }
    }
    debug("n = " + n)

    //---------------------------- parameters reading end ----------------------

    var total = 0
    for(i <- 0 until n) {
      var rowCount = 0
      for(j <- 0 until n) {
        if (arr(i)(j) == 1) {
          rowCount += 1
        }
      }
      total += soch(rowCount)
//      total += Subsets.subsetNumber(rowCount, 2)
    }

    for(i <- 0 until n) {
      var colCount = 0
      for(j <- 0 until n) {
        if (arr(j)(i) == 1) {
          colCount += 1
        }
      }
      total += soch(colCount)
//      total += Subsets.subsetNumber(colCount, 2)
    }

    println(total+"")
  }

  def soch(all:Int): Int = all - 1 match {
    case x if x < 1 => 0
    case rest => rest + soch(rest)
  }

  //============================ service code ======================

//  var inst = System.in

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()

  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
//    inst = new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1"))
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
3
.CC
C..
C.C
"""

val sa2 = """
4
CC..
C..C
.CC.
.CC.
"""

}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object A_343_A {   var br = createBufferedReader(); var debugV = false

      //COMMENT ME !
    runTest(Test.sa2)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading --------------------------
    val n = readLine.int
    val arr = new Array[String](n)
    (0 until n).foreach(arr(_) = readLine.string)
//    val arr = Array.fill(n,n)(0)
//    for(i <- 0 until n) {
//      val line = readLine.string
//      for(j <- 0 until n) {
//        arr(i)(j) = if (line(j) == '.') 0 else 1
//      }
//    }
    debug("n = " + n)

    //---------------------------- parameters reading end ----------------------

    val rr = arr.map(x => soch(x.count { _ == 'C' })).sum
    var total = rr

    for(i <- 0 until n) {
      var colCount = 0
      for(j <- 0 until n) {
        if (arr(j)(i) == 'C') {
          colCount += 1
        }
      }
      total += soch(colCount)
//      total += Subsets.subsetNumber(colCount, 2)
    }

    outLn(total+"")

    finish
  }

  def soch(all:Int): Int = all - 1 match {
    case x if x < 1 => 0
    case rest => rest + soch(rest)
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) {
    resultStr.append(str).append("\n")
  }
  def finish() {
//    if (file == null) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
3
.CC
C..
C.C
"""

val sa2 = """
4
CC..
C..C
.CC.
.CC.
"""

}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object A_343_A {   var br = createBufferedReader(); var debugV = false

      //COMMENT ME !
    runTest(Test.sa2)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading --------------------------
    val n = readLine.int
    val arr = Array.fill(n,n)(0)
    for(i <- 0 until n) {
      val line = readLine.string
      for(j <- 0 until n) {
        arr(i)(j) = if (line(j) == '.') 0 else 1
      }
    }
    debug("n = " + n)

    //---------------------------- parameters reading end ----------------------

    var total = 0
    for(i <- 0 until n) {
      var rowCount = 0
      for(j <- 0 until n) {
        if (arr(i)(j) == 1) {
          rowCount += 1
        }
      }
      total += soch(rowCount)
//      total += Subsets.subsetNumber(rowCount, 2)
    }

    for(i <- 0 until n) {
      var colCount = 0
      for(j <- 0 until n) {
        if (arr(j)(i) == 1) {
          colCount += 1
        }
      }
      total += soch(colCount)
//      total += Subsets.subsetNumber(colCount, 2)
    }

    outLn(total+"")

    finish
  }

  def soch(all:Int): Int = all - 1 match {
    case x if x < 1 => 0
    case rest => rest + soch(rest)
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) {
    resultStr.append(str).append("\n")
  }
  def finish() {
//    if (file == null) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
3
.CC
C..
C.C
"""

val sa2 = """
4
CC..
C..C
.CC.
.CC.
"""

}

}

import java.util.ArrayList
import java.util.StringTokenizer
import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object A_343_A {

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

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa2.trim.getBytes("ISO-8859-1"))
//    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

    //---------------------------- parameters reading --------------------------
//    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val arr = Array.fill(n,n)(0)
    for(i <- 0 until n) {
      val line = readLine.string
      for(j <- 0 until n) {
        arr(i)(j) = if (line(j) == '.') 0 else 1
      }
    }
    //---------------------------- parameters reading end ----------------------

    var total = 0
    for(i <- 0 until n) {
      var rowCount = 0
      for(j <- 0 until n) {
        if (arr(i)(j) == 1) {
          rowCount += 1
        }
      }
      total += soch(rowCount)
//      total += Subsets.subsetNumber(rowCount, 2)
    }

    for(i <- 0 until n) {
      var colCount = 0
      for(j <- 0 until n) {
        if (arr(j)(i) == 1) {
          colCount += 1
        }
      }
      total += soch(colCount)
//      total += Subsets.subsetNumber(colCount, 2)
    }

    println(total+"")
  }

  def soch(all:Int): Int = all - 1 match {
    case x if x < 1 => 0
    case rest => rest + soch(rest)
  }

  //============================ service code ======================

  val br = createBufferedReader(System.in)

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()

  }

  def createBufferedReader(in: InputStream): BufferedReader = {
    val bis = new BufferedInputStream(in);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
3
.CC
C..
C.C
"""

val sa2 = """
4
CC..
C..C
.CC.
.CC.
"""

}

}

import java.util.Scanner

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

    var cake = new Array[String](n)
    for(i <- 0 until n)
      cake(i) = sc.nextLine()

    //
    var ans = BigInt(0)

    for(i <- 0 until n){
      val s = cake(i)

      var cnt = 0
      for(e <- s)
        if(e == 'C')
          cnt += 1

      if(cnt >= 2)
        ans += (BigInt(2) to cnt).product / 2
    }

    for(i <- 0 until n){
      var cnt = 0
      for(j <- 0 until n)
        if(cake(j)(i) == 'C')
          cnt += 1

      if(cnt >= 2)
        ans += (BigInt(2) to cnt).product / 2
    }

    println(ans)
  }
}

/**
 * Created by aborisenko on 21.02.16.
 */

import io.StdIn._

object Main extends App {
  def a629 (){
    val n = readInt()
    var arr: Array[String] = new Array[String](n)

    for( i <- 0 to n-1)
      arr(i) = readLine()

    var arr1: Array[Long] = Array.fill[Long](n)(0)
    var arr2: Array[Long] = Array.fill[Long](n)(0)

    for( i <- 0 to n-1)
      for( j <- 0 to n-1) {
        if( arr(i)(j) == 'c') {
          arr1(i) += 1
          arr2(j) += 1
        }
      }

    def f(n: Long): Long = {
      if(n < 2) 1 else n * f(n-1)
    }

    var sum: Long = 0

    for( i <- 0 to n-1) {
      sum = (if(arr1(i) < 2) 0 else f(arr1(i) - 1)) + sum
      sum = (if(arr2(i) < 2) 0 else f(arr2(i) - 1)) + sum
    }

    println(sum)
  }

  a629()
}

/**
 * Created by aborisenko on 21.02.16.
 */

import io.StdIn._

object Main extends App {
  def a629 (){
    val n = readInt()
    var arr: Array[String] = new Array[String](n)

    for( i <- 0 to n-1)
      arr(i) = readLine()

    var arr1: Array[Long] = Array.fill[Long](n)(0)
    var arr2: Array[Long] = Array.fill[Long](n)(0)

    for( i <- 0 to n-1)
      for( j <- 0 to n-1) {
        if( arr(i)(j) == 'C') {
          arr1(i) += 1
          arr2(j) += 1
        }
      }

    def f(n: Long): Long = {
      if(n < 2) 1 else n * f(n-1)
    }

    var sum: Long = 0

    for( i <- 0 to n-1) {
      sum = (if(arr1(i) < 2) 0 else f(arr1(i) - 1)) + sum
      sum = (if(arr2(i) < 2) 0 else f(arr2(i) - 1)) + sum
    }

    println(sum)
  }

  a629()
}


In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.

The first line contains a single integer m (1 ≤ m ≤ 1000) — the size of the set S. The second line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 106) — the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1 < s2 < ... < sm.

If there is no solution, print a single line containing -1. Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000. In the second line print n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the sequence. We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106. If there are multiple solutions, print any of them.

NoteIn the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n.

import java.io.FileReader
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable

object Solution {
  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val nums = readBigIntLine()
    val numSet = nums.toSet
    val baseGCD = nums.reduce(_.gcd(_))
    if (!(numSet contains baseGCD)) {
      println(-1)
    } else {
      println(numSet.size * 2 - 1)
      println(numSet.mkString(s" $baseGCD "))
      }
    }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

  def readIntLine(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    readLine().split(" ").map(BigInt.apply)
  }
}


There are $$$n$$$ districts in the town, the $$$i$$$-th district belongs to the $$$a_i$$$-th bandit gang. Initially, no districts are connected to each other.You are the mayor of the city and want to build $$$n-1$$$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).If two districts belonging to the same gang are connected directly with a road, this gang will revolt.You don't want this so your task is to build $$$n-1$$$ two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build $$$n-1$$$ roads to satisfy all the conditions.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of districts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the gang the $$$i$$$-th district belongs to. It is guaranteed that the sum of $$$n$$$ does not exceed $$$5000$$$ ($$$\sum n \le 5000$$$).

For each test case, print:   NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement.  YES on the first line and $$$n-1$$$ roads on the next $$$n-1$$$ lines. Each road should be presented as a pair of integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n; x_i \ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are two districts the $$$i$$$-th road connects.  For each road $$$i$$$, the condition $$$a[x_i] \ne a[y_i]$$$ should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).

//package codeforces.contests._1433

object DistrictsConnection {
  def main(args: Array[String]): Unit = {
    println{
      {
        for (_ <- 1 to io.StdIn.readInt()) yield {
          val n = io.StdIn.readInt()

          val digits = io.StdIn.readLine.split(" ").map(_.toInt)

          val groups = (1 to n).groupBy(i => digits(i - 1)).values.toIndexedSeq

          if (groups.size <= 1) "NO" else {
            val first = groups.head
            val last = groups.last

            val temp = groups.tail
              .foldLeft((new StringBuilder("YES"), first)) { case ((sb, prevG), currG) =>
                (sb.append(prevG.map("\n" + _ + " " + currG.head).mkString("")), currG)
              }

            temp._1.append(last.tail.map("\n" + _ + " " + first.head).mkString("")).toString()
          }
        }
      }.mkString("\n")
    }
  }
}


As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor!

The first line contains an integer n (3 ≤ n ≤ 105) — a number of rod-blanks. The second line contains n integers li (1 ≤ li ≤ 109) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.

Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.

NoteIn the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}. In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next()
  val (f, s, t) = in.next().split(' ').map(_.toInt).sorted.reverse.foldLeft(0, 0, 0) {
    case((a, b, c), el) if a <= b && a <= c => (a + el, b, c)
    case((a, b, c), el) if b <= a && b <= c => (a, b + el, c)
    case((a, b, c), el) if c <= a && c <= b => (a, b, c + el)
  }
  val sorted = List(f, s, t).sorted
  val res = sorted(2) - sorted(1) - sorted(0) + 1
  if (res >= 0)
    println(res)
  else
    println(0)
}

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

object _667B extends CodeForcesApp {
  override def apply(io: IO) = {
    val rods = io[List[Long]].sorted
    val p = rods.scanLeft(0L)(_ + _)
    val s = rods.scanRight(0L)(_ + _)
    val (l, r) = (p zip s) minBy {case (a, b) => (a - b).abs}
    io += (l - r).abs + 1
  }
}
/****************************[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
  }
  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 PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).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 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 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 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 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)
  }
  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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @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]]
  val mod: Int = (1e9 + 7).toInt
  val newLine: String = "\n"
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = this.+=(xs.size).appendNewLine().+=(xs)

  def appendNewLine(): this.type = {
    println()
    this
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.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[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}