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

object _651C extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val n = in[Int]
    val xc, yc = map[Int] to 0L
    val pc = map[(Int, Int)] to 0L

    repeat(n) {
      val x, y = in[Int]
      xc(x) += 1
      yc(y) += 1
      pc(x -> y) += 1
    }

    val res = pc map {
      case ((x, y), c) =>
        val i = xc(x) - c
        val j = yc(y) - c
        //debug(x, y, c, i, j, (i + j)*c)
        (i + j)*c + (c*(c-1))
    }
    out += res.sum/2
  }

  def map[K] = new {
    def to[V](default: V): mutable.Map[K, V] = mutable.Map.empty[K, V] withDefaultValue default
  }

  @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Any
  def main(args: Array[String]): Unit = {
    val (in, out) = (new InputReader(System.in), new OutputWriter(System.out))
    solve(in, out)
    in.close()
    out.close()
  }
}
/***********************************[Scala I/O]*********************************************/
import java.io._, 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 builder: Parser.Collection[C, A]): C[A] = (builder() ++= Iterator.fill(n)(apply)).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]))
}

class OutputWriter(out: PrintWriter) extends AutoCloseable {
  def this(out: OutputStream) = this(new PrintWriter(out))

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

  def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else out.print(separator)
    out.print(obj)
    this
  }

  def newLine(): this.type = {
    isNewLine = true
    out.println()
    this
  }

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }

  def append(obj: Any*): this.type = this ++= obj

  override def close() = {
    out.flush()
    out.close()
  }
}

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

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      val forX = mutable.HashMap.empty[Int, Int]
      val forY = mutable.HashMap.empty[Int, Int]
      val elementToCount = mutable.HashMap.empty[(Int, Int), Int]
      for (i <- 0 until n) {
        val x = reader.nextInt()
        val y = reader.nextInt()
        val xx = forX.get(x)
        forX.put(x, xx.getOrElse(0) + 1)

        val yy = forY.get(y)
        forY.put(y, yy.getOrElse(0) + 1)

        val zz = elementToCount.get((x, y))
        elementToCount.put((x, y), zz.getOrElse(0) + 1)
      }
      var result: Long = calc(forX) + calc(forY)
      for (el <- elementToCount) {
        result -= (el._2.toLong * (el._2.toLong - 1L)) / 2L
      }
      writer.print(result)
    }
  }

  def calc(h: mutable.HashMap[Int, Int]): Long = {
    var answer: Long = 0
    for (el <- h) {
      answer += (el._2.toLong * (el._2.toLong - 1L)) / 2L
    }
    answer
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

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

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    * @param values Array of Int
    * @param commutative function like min, max, sum
    * @param zero zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val d = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      d(i) = (nextInt, nextInt)
    }
    var ans = 0L
    val byX = d.sortBy(x => x._1)
    val byY = d.sortBy(x => x._2)
    var tmp = 1L
    var prev = byX(0)._1
    for (i <- 1 until n) {
      if (byX(i)._1 == byX(i - 1)._1) {
        tmp += 1
      } else {
        prev = byX(i)._1
        ans += (tmp * (tmp - 1L)) / 2
        tmp = 1
      }
    }
    ans += (tmp * (tmp - 1L)) / 2
    tmp = 1
    prev = byY(0)._2
    for (i <- 1 until n) {
      if (byY(i)._2 == byY(i - 1)._2) {
        tmp += 1
      } else {
        prev = byY(i)._2
        ans += (tmp * (tmp - 1L)) / 2
        tmp = 1
      }
    }
    ans += (tmp * (tmp - 1L)) / 2
    val sorted = d.sortBy(r => (r._1, r._2))
    var common = 1L
    var ind = 1
    while (ind < n) {
      while (ind < n && sorted(ind)._1 == sorted(ind - 1)._1 && sorted(ind)._2 == sorted(ind - 1)._2) {
        common += 1
        ind += 1
      }
      ans -= (common * (common - 1L)) / 2
      common = 1
      ind += 1
    }
    out.println(ans)
    return 0
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt
object ProblemCScala {
  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def main(args: Array[String]) {
    val n : Int = readInt();

    val xys = for {
      i <- 1 to n
      xy = readInts()
    } yield (xy(0), xy(1))

    val xsorted = xys.sortBy(r =>  (r._1,r._2))
    val ysorted = xys.sortBy(_._2)

    //println(xsorted)

    //println(ysorted)

    var total : Long = 0
    var i : Int = 0;
    while (i < n) {
      val start : Int = i;
      var l : Long = 1
      i = i + 1
      while (i < n && xsorted(start)._1 == xsorted(i)._1) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Long = 1
      i = i + 1
      while (i < n && ysorted(start)._2 == ysorted(i)._2) {
        l = l + 1
        i = i + 1
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }

    i = 0;
    var dc : Long = 0;
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Long = 1
      i = i + 1
      while (i < n && xsorted(start) == xsorted(i)) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      dc = dc + (l-1)*l/2;
    }

    total = total - dc

    println(total)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map{ _ =>
    val a = in.next().split(' ').map(_.toInt)
    (a.head, a.last)
  }
  val same = data.groupBy(i => i).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum
  val vertical = data.groupBy(i => i._2).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum
  val horizontal = data.groupBy(i => i._1).filter(_._2.length > 1).map(_._2.length.toLong).map(k => (k - 1) * k / 2).sum
  println(vertical + horizontal - same)
}

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

import scala.collection.immutable
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 C345A(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 C345A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val a: immutable.IndexedSeq[Point] = 0 until n by 1 map { _ =>
      Point(ni(), ni())
    }
    val ans = 0L
    val cntx: Long = a.groupBy(_.x).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum
    val cnty: Long = a.groupBy(_.y).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum
    val x = a.groupBy(identity).map(_._2.size).filter(1<).map(f => (f.toLong * (f-1)) / 2).sum
    println(cntx + cnty - x)
  }

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

object A650 {

  import IO._
  import collection.{mutable => cu}

  def hash(a: Int, b: Int): Long = {
    a*(10000000001L) + b
  }
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[Long, Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy(hash(a, b))
      xy(hash(a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def hash(a: Int, b: Int): Long = {
    a*2000000001L + b
  }
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[Long, Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy(hash(a, b))
      xy(hash(a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[(Int, Int), Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy((a, b))
      xy((a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def hash(a: Int, b: Int): Long = {
    a*(1L << 32) + b
  }
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[Long, Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy(hash(a, b))
      xy(hash(a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      var answer: Long = 0
      val forX = mutable.HashMap.empty[Int, Int]
      val forY = mutable.HashMap.empty[Int, Int]
      val elements = mutable.HashSet.empty[(Int, Int)]
      val doubles = mutable.HashSet.empty[(Int, Int)]
      for (i <- 0 until n) {
        val x = reader.nextInt()
        val y = reader.nextInt()
        if (!elements.contains((x, y))) {
          val xx = forX.get(x)
          forX.put(x, xx.getOrElse(0) + 1)

          val yy = forY.get(y)
          forY.put(y, yy.getOrElse(0) + 1)

          elements.+=((x, y))
        } else {
          doubles.+=((x, y))
        }
      }
      var result: Long = calc(forX) + calc(forY)
      for (el <- doubles) {
        result += forX.getOrElse(el._1, 0)
        result += (forY.getOrElse(el._2, 0) - 1)
      }
      writer.print(result)
    }
  }

  def calc(h: mutable.HashMap[Int, Int]): Long = {
    var answer: Long = 0
    for (el <- h) {
      answer += (el._2 * (el._2 - 1)) / 2
    }
    answer
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

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

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      val forX = mutable.HashMap.empty[Int, Int]
      val forY = mutable.HashMap.empty[Int, Int]
      val elements = mutable.HashSet.empty[(Int, Int)]
      val doubles = mutable.HashMap.empty[(Int, Int), Int]
      for (i <- 0 until n) {
        val x = reader.nextInt()
        val y = reader.nextInt()
        if (!elements.contains((x, y))) {
          val xx = forX.get(x)
          forX.put(x, xx.getOrElse(0) + 1)

          val yy = forY.get(y)
          forY.put(y, yy.getOrElse(0) + 1)

          elements.+=((x, y))
        } else {
          val xx = doubles.get((x, y))
          doubles.put((x, y), xx.getOrElse(0) + 1)
        }
      }
      var result: Long = calc(forX) + calc(forY)
      for (el <- doubles) {
        result += forX.getOrElse(el._1._1, 0).toLong * el._2.toLong + (el._2.toLong * (el._2.toLong - 1L)) / 2L
        result += (forY.getOrElse(el._1._2, 0).toLong - 1L) * el._2.toLong
      }
      writer.print(result)
    }
  }

  def calc(h: mutable.HashMap[Int, Int]): Long = {
    var answer: Long = 0
    for (el <- h) {
      answer += (el._2.toLong * (el._2.toLong - 1L)) / 2L
    }
    answer
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

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

import scala.collection.mutable

object Solution extends ConsoleIO {
  def main(args: Array[String]) = {
    withIO { (reader, writer) =>
      val n = reader.nextInt()
      val forX = mutable.HashMap.empty[Int, Int]
      val forY = mutable.HashMap.empty[Int, Int]
      val elements = mutable.HashSet.empty[(Int, Int)]
      val doubles = mutable.HashMap.empty[(Int, Int), Int]
      for (i <- 0 until n) {
        val x = reader.nextInt()
        val y = reader.nextInt()
        if (!elements.contains((x, y))) {
          val xx = forX.get(x)
          forX.put(x, xx.getOrElse(0) + 1)

          val yy = forY.get(y)
          forY.put(y, yy.getOrElse(0) + 1)

          elements.+=((x, y))
        } else {
          val xx = doubles.get((x, y))
          doubles.put((x, y), xx.getOrElse(0) + 1)
        }
      }
      var result: Long = calc(forX) + calc(forY)
      for (el <- doubles) {
        result += forX.getOrElse(el._1._1, 0) * el._2 + (el._2 * (el._2 - 1)) / 2
        result += (forY.getOrElse(el._1._2, 0) - 1) * el._2
      }
      writer.print(result)
    }
  }

  def calc(h: mutable.HashMap[Int, Int]): Long = {
    var answer: Long = 0
    for (el <- h) {
      answer += (el._2 * (el._2 - 1)) / 2
    }
    answer
  }
}

trait ConsoleIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

trait FileIO {
  def withIO(task: (Scanner, PrintWriter) => Unit) = {
    val reader = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))))
    val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))))
    task(reader, writer)
    reader.close()
    writer.close()
  }
}

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

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    * @param values Array of Int
    * @param commutative function like min, max, sum
    * @param zero zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val d = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      d(i) = (nextInt, nextInt)
    }
    var ans = 0
    val byX = d.sortBy(x => x._1)
    val byY = d.sortBy(x => x._2)
    var tmp = 1
    var prev = byX(0)._1
    for (i <- 1 until n) {
      if (byX(i)._1 == byX(i - 1)._1) {
        if (byX(i)._1 == prev) {
          tmp += 1
        } else {
          prev = byX(i)._1
          ans += (tmp * (tmp - 1)) / 2
          tmp = 1
        }
      } else {
        prev = byX(i)._1
      }
    }
    ans += (tmp * (tmp - 1)) / 2
    tmp = 1
    prev = byY(0)._2
    for (i <- 1 until n) {
      if (byY(i)._2 == byY(i - 1)._2) {
        if (byY(i)._2 == prev) {
          tmp += 1
        } else {
          prev = byY(i)._2
          ans += (tmp * (tmp - 1)) / 2
          tmp = 1
        }
      } else {
        prev = byY(i)._2
      }
    }
    ans += (tmp * (tmp - 1)) / 2
    val sorted = d.sortBy(r => (r._1, r._2))
    var common = 1
    for (i <- 1 until n) {
      if (sorted(i)._1 == sorted(i - 1)._1 && sorted(i)._2 == sorted(i - 1)._2) {
        common += 1
      }
    }
    out.println(ans - (common * (common - 1)) / 2)
    return 0
  }
}

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

import scala.collection.mutable

object C {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    * @param values Array of Int
    * @param commutative function like min, max, sum
    * @param zero zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val d = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      d(i) = (nextInt, nextInt)
    }
    var ans = 0
    val byX = d.sortBy(x => x._1)
    val byY = d.sortBy(x => x._2)
    for (i <- 1 until n) {
      if (byX(i)._1 == byX(i - 1)._1) {
        ans += 1
      }
    }
    for (i <- 1 until n) {
      if (byY(i)._2 == byY(i - 1)._2) {
        ans += 1
      }
    }
    val sorted = d.sortBy(r => (r._1, r._2))
    var common = 0
    for (i <- 1 until n) {
      if (sorted(i)._1 == sorted(i - 1)._1 && sorted(i)._2 == sorted(i - 1)._2) {
        common += 1
      }
    }
    out.println(ans - (common * (common - 1)) / 2)
    return 0
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt
object ProblemCScala {
  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def main(args: Array[String]) {
    val n : Int = readInt();

    val xys = for {
      i <- 1 to n
      xy = readInts()
    } yield (xy(0), xy(1))

    val xsorted = xys.sortBy(r =>  (r._1,r._2))
    val ysorted = xys.sortBy(_._2)

    //println(xsorted)

    //println(ysorted)

    var total : Int = 0
    var i : Int = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && xsorted(start)._1 == xsorted(i)._1) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && ysorted(start)._2 == ysorted(i)._2) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }

    i = 0;
    var dc : Int = 0;
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && xsorted(start) == xsorted(i)) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      dc = dc + (l-1)*l/2;
    }

    total = total - dc

    println(total)

  }

}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt
object ProblemCScala {
  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def main(args: Array[String]) {
    val n : Int = readInt();

    val xys = for {
      i <- 1 to n
      xy = readInts()
    } yield (xy(0), xy(1))

    val xsorted = xys.sortBy(r =>  (r._1,r._2))
    val ysorted = xys.sortBy(_._2)

    //println(xsorted)

    //println(ysorted)

    var total : Long = 0
    var i : Int = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && xsorted(start)._1 == xsorted(i)._1) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && ysorted(start)._2 == ysorted(i)._2) {
        l = l + 1
        i = i + 1
      }
      //println(s"sequence of length $l")
      total = total + (l-1)*l/2;
    }

    i = 0;
    var dc : Int = 0;
    i = 0;
    while (i < n) {
      val start : Int = i;
      var l : Int = 1
      i = i + 1
      while (i < n && xsorted(start) == xsorted(i)) {
        l = l + 1;
        i = i + 1;
      }
      //println(s"sequence of length $l")
      dc = dc + (l-1)*l/2;
    }

    total = total - dc

    println(total)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map{ _ =>
    val a = in.next().split(' ').map(_.toLong)
    (a.head, a.last)
  }
  val same = data.groupBy(i => i).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum
  val vertical = data.groupBy(i => i._2).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum
  val horizontal = data.groupBy(i => i._1).filter(_._2.length > 1).map(_._2.length).map(k => (k - 1) * k / 2).sum
  println(vertical + horizontal - same)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map{ _ =>
    val a = in.next().split(' ').map(_.toInt)
    (a.head, a.last)
  }
  val same = data.groupBy(i => i).filter(i => i._2.length > 1).map(i => i._2.length).map(k => (k - 1) * k / 2).sum
  val vertical = data.groupBy(i => i._2).filter(i => i._2.length > 1).map(i => i._2.length).map(k => (k - 1) * k / 2).sum
  val horizontal = data.groupBy(i => i._1).filter(i => i._2.length > 1).map(i => i._2.length).map(k => (k - 1) * k / 2).sum
  println(vertical + horizontal - same)
}

object A650 {

  import IO._
  import collection.{mutable => cu}

  def hash(a: Int, b: Int): Long = {
    a*1000000001L + b
  }
  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val x = cu.Map.empty[Int, Int].withDefaultValue(0)
    val y = cu.Map.empty[Int, Int].withDefaultValue(0)
    val xy = cu.Map.empty[Long, Int].withDefaultValue(0)
    var res = 0L
    for(_ <- 0 until n) {
      val Array(a, b) = readInts(2)
      res += x(a)
      x(a) += 1
      res += y(b)
      y(b) += 1
      res -= xy(hash(a, b))
      xy(hash(a, b)) += 1
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val price = in.next().split(' ').map(_.toLong)
  val capitals = in.next().split(' ').map(_.toInt - 1).toSet
  val sum = capitals.toList.map(price).sum
  val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum
  val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2
  val capToUncap = capitals.toList.map(i => price(i) * nonCapitals).sum
  val lineSum = (n - 1 :: price.indices.toList).sliding(2)
    .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))
    .map(i => price(i.head) * price(i.last)).sum
  println(capitalsPriceSum + lineSum + capToUncap)
}

import scala.io.StdIn._

object B extends App {
  val Array(n, k) = readLine().split(" ").map(_.toInt)
  val C = readLine().split(" ").map(_.toLong)
  val Cap = readLine().split(" ").map(i => i.toInt - 1)

  val IsCapital = Array.ofDim[Boolean](n)
  Cap.foreach { i => IsCapital(i) = true }

  var sum = C.sum
  var total = 0L
  for (i <- 0 until k) {
    val j = Cap(i)
    total += C(j) * (sum - C(j))
    sum -= C(j)
  }

  for (i <- 0 until n) {
    val next = (i + 1) % n
    if (!IsCapital(i) && !IsCapital(next)) {
      total += C(i) * C(next)
    }
  }

  println(total)
}

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

object _703B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n, k = read[Int]
    val beauty = read[Vector, Long](n)
    val capitals = read[Set, Int](k).map(_ - 1)

    var total = beauty.sum
    var ans = 0L

    def add(u: Int, v: Int): Unit = if(!capitals(u) && !capitals(v)) {
      ans += beauty(u)*beauty(v)
      //debug(u, v, ans)
    }

    beauty.indices foreach {i =>
      add(i, (i + 1)%n)
    }

    capitals foreach {i =>
      total -= beauty(i)
      ans += beauty(i) * total
      //debug(i, ans)
    }

    write(ans)
  }
}
/****************************[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 in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    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 = assuming(t.size == 1)(t.head)
    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
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  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 deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    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 toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  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(x, y, if (n.lteq(x, y)) n.one else -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] = map[K] to mutable.Set.empty[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
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some 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 writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    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 scala.io.StdIn._

object B extends App {
  val Array(n, k) = readLine().split(" ").map(_.toInt)
  val C = ("0 " + readLine()).split(" ").map(_.toLong)
  val Cap = ("0 " + readLine()).split(" ").map(_.toInt)
  val IsCapital = Array.ofDim[Boolean](n + 1)
  Cap.foreach { i =>
    IsCapital(i) = true
  }

  var capTotal = Cap.map(i => C(i)).sum
  val CapSum = Array.ofDim[Long](k + 2)
  for (i <- 1 to k) {
    CapSum(i) = capTotal
    capTotal -= C(Cap(i))
  }

  val CitiesSum = C.sum - CapSum(1)

  var totalCapitals = 0L
  for (i <- 1 to k) {
    val capitalIdx = Cap(i)
    val capitalValue = C(capitalIdx)
    val next = if (capitalIdx + 1 <= n) capitalIdx + 1 else 1
    val prev = if (capitalIdx - 1 >= 1) capitalIdx - 1 else n
    totalCapitals += capitalValue * (CitiesSum + CapSum(i + 1) - C(next) - C(prev))
  }

  var border = 0L
  for (i <- 1 to n) {
    val j = if (i + 1 <= n) i + 1 else 1
    if (!IsCapital(i) || !IsCapital(j)) border += C(i) * C(j)
  }

  println(border + totalCapitals)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val price = in.next().split(' ').map(_.toInt)
  val capitals = in.next().split(' ').map(_.toInt - 1).toSet
  val sum = capitals.toList.map(price).sum
  val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum
  val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2
  val capToUncap = capitals.map(i => price(i) * nonCapitals).sum
  val lineSum = (n - 1 :: price.indices.toList).sliding(2)
    .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))
    .map(i => price(i.head) * price(i.last)).sum
  println(capitalsPriceSum + lineSum + capToUncap)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val price = in.next().split(' ').map(_.toInt)
  val capitals = in.next().split(' ').map(_.toInt - 1).toSet
  val sum = capitals.map(price).sum
  val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum
  val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2
  val capToUncap = capitals.map(i => price(i) * nonCapitals).sum
  val lineSum = (n - 1 :: price.indices.toList).sliding(2)
    .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))
    .map(i => price(i.head) * price(i.last)).sum
  println(capitalsPriceSum + lineSum + capToUncap)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val price = in.next().split(' ').map(_.toInt)
  val capitals = in.next().split(' ').map(_.toInt - 1).toSet
  val sum = capitals.toList.map(price).sum
  val nonCapitals = price.indices.filterNot(capitals.contains).map(price).sum
  val capitalsPriceSum = capitals.toList.map(i => price(i) * (sum - price(i))).sum / 2
  val capToUncap = capitals.toList.map(i => price(i) * nonCapitals).sum
  val lineSum = (n - 1 :: price.indices.toList).sliding(2)
    .filterNot(i => capitals.contains(i.head) || capitals.contains(i.last))
    .map(i => price(i.head) * price(i.last)).sum
  println(capitalsPriceSum + lineSum + capToUncap)
}

import scala.io.StdIn._

object B extends App {
  val Array(n, k) = readLine().split(" ").map(_.toInt)
  val C = ("0 " + readLine()).split(" ").map(_.toLong)
  val Cap = ("0 " + readLine()).split(" ").map(_.toInt)

  var capTotal = Cap.map(i => C(i)).sum
  val CapSum = Array.ofDim[Long](k + 2)
  for (i <- 1 to k) {
    CapSum(i) = capTotal
    capTotal -= C(Cap(i))
  }

  val CitiesSum = C.sum - CapSum(1)

  var totalCapitals = 0L
  for (i <- 1 to k) {
    val capitalIdx = Cap(i)
    val capitalValue = C(capitalIdx)
    val next = if (capitalIdx + 1 <= n) capitalIdx + 1 else 1
    val prev = if (capitalIdx - 1 >= 1) capitalIdx - 1 else n
    totalCapitals += capitalValue * (CitiesSum + CapSum(i + 1) - C(next) - C(prev))
  }

  var border = 0L
  for (i <- 1 to n) {
    val j = i + 1
    if (j <= n) border += C(i) * C(j)
    else border += C(i) * C(1)
  }

  println(border + totalCapitals)
}


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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextInts(n)
      val res = Array.ofDim[Int](n)

      var drenchUntil = n
      for (i <- as.indices.reverse) {
        val d = i - as(i)
        if (d < drenchUntil) drenchUntil = d
        if (i > drenchUntil) res(i) = 1
      }

      out.println(res.mkString(" "))
    }

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

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toList.map(x => x.toInt)

    println(layer(as.reverse, 0, List.empty).map(x => if (x) 1 else 0).reverse.mkString(" "))

    @tailrec
    def layer(as: List[Int], a0: Int, ds: List[Boolean]): List[Boolean] = as match {
          case x :: xs => {
            val x0 = Math.max(a0 - 1, x)
            val d = if (x0 > 0) true else false
            layer(xs, x0, d:: ds)
          }
          case _ => ds.reverse
    }
  }
}

import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toArray.map(x => x.toInt)

    println(layer_iterate(as).map(x => if (x) 1 else 0).mkString(" "))

    def layer_iterate(as: Array[Int]): Array[Boolean] = {
      var arr: Array[Boolean] = Array.fill(as.length)(false)
      var a = as.last
      if (a > 0) {
        arr(as.length - 1) = true
      }
      for (i <- (as.length - 2 to 0 by -1)) {
        val a_i = as(i)
        a = Math.max(a - 1, a_i)
        if (a > 0) {
          arr(i) = true
        }
      }
      arr
    }
  }
}


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 CF_504_A {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.t2)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val m = l1.int
    val s = readLine.string
    val t = readLine.string

    val ind = s.indexOf("*")
    var res = false
    if (ind == -1) {
      res = s==t
    } else {
      val start = s.substring(0,ind)
      val stop = s.substring(ind+1, s.length())
      res = t.startsWith(start) && t.drop(start.length()).endsWith(stop)
    }
    outLn( if (res) "YES" else "NO" )

    debug("================= RESULT ================== ")
    finish
  }

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

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } 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 runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

val sa1 = """
6 10
code*s
codeforces
"""

val sa2 = """
6 5
vk*cup
vkcup
"""

val sa3 = """
1 1
v
k
"""

val t1 = """
9 10
*deforces
codeforces
"""

val t2 = """
9 10
codeforc*
codeforces
"""
}

}

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 = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, M = ni()
    val s, t = ns()
    val ok = s.indexOf('*') match {
      case -1 =>
        s == t
      case ix =>
        val l = s.take(ix)
        val r = s.drop(ix + 1)
        N - 1 <= M && t.startsWith(l) && t.endsWith(r)
    }

    val ans = if (ok) "YES" else "NO"

    out.println(ans)
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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 CF_504_A {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.t2)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val m = l1.int
    val s = readLine.string
    val t = readLine.string

    val ind = s.indexOf("*")
    var res = false
    if (ind == -1) {
      res = s==t
    } else {
      val start = s.substring(0,ind)
      val stop = s.substring(ind+1, s.length())
      res = t.startsWith(start) && t.endsWith(stop)
    }
    outLn( if (res) "YES" else "NO" )

    debug("================= RESULT ================== ")
    finish
  }

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

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } 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 runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

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

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

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

val sa1 = """
6 10
code*s
codeforces
"""

val sa2 = """
6 5
vk*cup
vkcup
"""

val sa3 = """
1 1
v
k
"""

val t1 = """
9 10
*deforces
codeforces
"""

val t2 = """
9 10
codeforc*
codeforces
"""
}

}


object A {
  import scala.io.{StdIn => in}

  def main(args: Array[String]): Unit = {
    val tests = in.readInt()
    (1 to tests).foreach { _ =>
      in.readInt()
      val levels = in.readLine().split(' ').map(_.toInt)
      val min = levels.fold(Int.MaxValue) { case (a, b) => Math.min(a, b) }
      println(levels.count(_ > min))
    }
  }
}

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

object A1487 {
    def main(args: Array[String]){
        val t = readInt()

        for(i <- 1 to t) {
            val n = readInt()
            var arr = readLine.split(" ").map(_.toInt)
            val idx = arr.sorted.indexWhere(_ > arr.min)
            if (idx == -1) println(0)
            else println(arr.length - idx)
        }
    }
}

//package codeforces.contests._1487

object Arena {

  def main(args: Array[String]): Unit = {
    println({
      for (_ <- 1 to io.StdIn.readInt()) yield {
        val n   = io.StdIn.readInt
        val arr = io.StdIn.readLine.split(" ").map(_.toInt)

        val minE = arr.min
        val mineECount = arr.count(_ == minE)

        if(n == mineECount) 0 else n - mineECount
      }
    }.mkString("\n"))
  }
}

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextInts(n)
      val min = as.min

      out.println(as.count(_ > min))
    }

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


object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val Array(n, h) = lines.next().split(' ').map(_.toInt)
  val line = lines.next().split(' ').map(_.toInt)

  println(line.length + line.count(_ > h))
}

import java.io.BufferedReader
import java.io.InputStreamReader

object HelloScala {
  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val line1 = br.readLine().split(" ")
    val n = line1.head.toInt
    val h = line1.last.toInt
    val line2 = br.readLine().split(" ")
    val heights = line2.map(_.toInt)
    val heightPartitions = heights.partition(_ > h)
    val output = heightPartitions._1.length*2+heightPartitions._2.length
    println(output)
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader

object HelloScala {
  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val line1 = br.readLine().split(" ")
    val n = line1.head.toInt
    val h = line1.last.toInt
    val line2 = br.readLine().split(" ")
    val heights = line2.map(_.toInt)
    val tallerCount = heights.count(_ > h)
    val output = tallerCount*2+n-tallerCount
    println(output)
  }
}

object Solution extends App {
  val Array (n, h) = readLine.split(" ").map(_.toInt)
  val tab = readLine.split(" ").map(_.toInt)

  val wyzsi = tab.sorted.dropWhile(_ <= h)

  println(tab.size + wyzsi.size)
}

import scala.io.StdIn

object VanyaAndFence extends App {

  val l1 = StdIn.readLine().split(" ")
  val n = l1(0).toInt
  val h = l1(1).toInt

  val l2 = StdIn.readLine().split(" ")
  val heights = l2.map(_.toInt)
  print(impl(heights, h))

  def impl(heights: Array[Int], max: Int): Int = {
    var width: Int = 0
    for (height <- heights) {
      if (height > max) {
        width += 2
      } else {
        width += 1
      }
    }
    width
  }
}

object A677 {
  @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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n, h) = readInts(2)
    val input = readInts(n)
    println(input.map(x => if(x > h) 2 else 1).sum)
  }
}

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

object _677A extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, h = io[Int]
    val heights = io[Vector, Int](n)
    io += heights.sumWith(i => if (i > h) 2 else 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 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 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 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
  }
  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)
  }
  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[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  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]]
  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 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[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  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 array[A]: Write[Array[A]] = Write(_ mkString " ")
    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()
      }
    }
  }
}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    val Array(n, h) = readLine.split(" ").map(_.toInt)
    val people = readLine.split(" ").map(_.toInt)
    print(people.count(p => p <= h) + 2 * people.count(p => p > h))
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val Array(_, h) = Console.readLine().split(" ").map(_.toInt)
    println(Console.readLine().split(" ").map(s => if(s.toInt > h) 2 else 1).sum)
  }
}

import java.util.Scanner

object Main2 extends App {
  val scanner = new Scanner(System.in)
  val personNumber = scanner.nextInt()
  val fenceHeight = scanner.nextInt()
  var personNumberNotGreaterThanFence: Int = 0
  for (_ <- 0 until personNumber) if (scanner.nextInt() <= fenceHeight) personNumberNotGreaterThanFence += 1
  println(personNumber * 2 - personNumberNotGreaterThanFence)
}

object Solution extends App {
  val Array(n, h) = readLine.split(" ").map(_.toInt)
  val hs = readLine.split(" ").map(_.toInt)

  val higher = hs.sorted.dropWhile(_ <= h)

  println(hs.size + higher.size)
}

import scala.io.StdIn._

object TaskA extends App {
  var n :: h :: Nil = readInts
  println(n + readInts.count(_ > h))

  def readInts = readLine.split(" ").map(_.toInt).toList
}