object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val res = str.foldLeft(0, 0) {
    case ((sum, open), ')') if open == 0 => (sum + 1, open)
    case ((sum, open), ')')  => (sum, open - 1)
    case ((sum, open), '(')  => (sum, open + 1)
  }
  println(str.length - res._1 - res._2)
}

object Main26B {

  def main(args: Array[String]) {
    def processChar(r: (Int, Int), c: Char): (Int, Int) = {
      val (a, b) = r
      if (c == '(')
        (a+1, b+1)
      else
        if (b > 0)
          (a+1, b-1)
        else
          (a, b)
    }
    val str = readLine
    val (result_a, result_b) = str.foldLeft(0, 0)(processChar)
    println(result_a - result_b)
  }

}

object P026B {
  def main(args: Array[String]) = {
    val s = readLine.map(x => -(x.toInt)*2 + 81)
    val n = s.size
    var l = n
    var sum = 0
    for (i <- 0 to n-1) {
      if (sum + s(i) >= 0) {
        sum += s(i)
      }
      else {
        l -= 1;
      }
    }
    println(l-sum)
  }
}


/**
  * @author ShankarShastri
  *         Algorithm: Problem1 (http://codeforces.com/contest/1028/problem/A)
  */

import scala.io.StdIn._
import scala.annotation.tailrec

object FindSquares {

  def findSquare(ls: List[String]): (Int, Int) = {
    val l = ls.zipWithIndex.map(l => (l._2, l._1.indexOf('B'),
      l._1.lastIndexOf('B')))
      .filter(t => t._2 != -1 && t._3 != -1).map(e => (e._1 + 1, e._2 + 1, e._3 + 1))
    val le = l(l.length / 2)
    (le._1, (le._2 + le._3) / 2)
  }

  def main(args: Array[String]): Unit = {
    val List(r,_) = readLine.replaceAll("\\s+$", "").split(" ").map(_.trim.toInt).toList
    val strList = (1 to r).map(_ => readLine).toList
    val res = findSquare(strList.map(_.trim))
    println(s"${res._1} ${res._2}")
  }
}

object 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 sc = new InputReader(System.in)
    val N, M = sc.nextInt()
    var l, r, t, b = -1
    rep(N) { i =>
      val line = sc.next()
      rep(M) { j =>
         if (line(j) == 'B') {
           if (l == -1) l = j
           r = j
           if (t == -1) t = i
           b = i
         }
      }
    }

    out.println(s"${(t + b) / 2 + 1} ${(l + r) / 2 + 1}")
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object Test extends App {
  import java.io.PrintWriter
  import java.util.Scanner

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextDouble = in.nextDouble
  def nextString = in.next
  def stuff: Unit = {
    val n = nextInt
    val m = nextInt
    for (i <- 1 to n) {
      val cur = nextString
      if (cur.contains('B')) {
        val fst = cur.indexOf('B')
        val lst = cur.lastIndexOf('B')
        val (x, y) =
          if (fst == lst)
            i.toDouble -> (fst + 1).toDouble
          else {
            Math.ceil(i + (lst - fst) / 2) -> Math.ceil(((fst + lst) / 2) + 1)
          }
        out.println(x.toInt + " " + y.toInt)
        return
      }
    }
  }

  try {
    stuff
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}

import scala.io._

object a5 {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().drop(1).toArray
    val rows = lines.zipWithIndex.dropWhile(! _._1.contains("B")).takeWhile(_._1.contains("B"))
    val firstrow = rows.head._2+1
    val lastrow = rows.last._2+1
    val firstcol = rows.head._1.indexOf("B")+1
    val lastcol = rows.head._1.lastIndexOf("B")+1
    val (centerrow, centercol) = (firstrow + ((lastrow-firstrow)/2), firstcol + ((lastcol-firstcol)/2))
    println(s"$centerrow $centercol")
  }
}


object A extends App {
  val n = readInt();
  val in = Array.fill(n)(readLine())
  var sa = Set[Char]()
  var sb = Set[Char]()
  for (i <- 0 until n; j <- 0 until n)
    if (i==j || n-i-1==j || i==n-j-1 || n-j-1==n-i-1) sa += in(i)(j);
    else sb += in(i)(j)

  if (sa.size == 1 && sb.size == 1 && sa.head != sb.head)
    println("YES");
  else
    println("NO")
}

import java.util.StringTokenizer

object _404A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (0 until n).map(i => next).toArray
  val ch = a(0)(0)
  val dish = a(0)(1)

  val cb = for {
      i <- 0 until n
      j <- 0 until n
    } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish

  if (ch != dish && cb.forall(i => i)) println("YES")
  else println("NO")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val k = in.next().toInt
  val data = Range(0, k).map { i => (i, in.next())}
  val symbols = data.head._2.toSet
  val symbol =  data.head._2.head
  if (symbols.size != 2) println("NO")
  else {
    val r = data.forall{
      case(i, str) =>
        val count = str.count(_ == symbol)
        str.forall(symbols) && count < 3 && str.charAt(i) == symbol && str.charAt(str.length - i - 1) == symbol && {
          i != str.length - i - 1 || count == 1
        }
    }
    if (r)
      println("YES")
    else
      println("NO")
  }

}

object A404 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(read.toCharArray)
    var xChar = in(0)(0)
    var diffChar = in(1)(0)
    var ifX = true
    var ifDiff = true
    for(i <- 0 until n; j <- 0 until n) {
      if(i == j) {// diagonal 1
        ifX &= in(i)(j) == xChar
      } else if(i + j == n-1) {// diagonal 2
        ifX &= in(i)(j) == xChar
      } else {
        ifDiff &= in(i)(j) == diffChar
      }
    }

    if (xChar != diffChar && ifDiff && ifX) {
      println("YES")
    } else {
      println("NO")
    }
  }

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

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

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

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

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

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P404A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  type Row = List[Char]

  val N = sc.nextInt
  sc.nextLine
  val P: List[Row] = List.fill(N)(sc.nextLine.toList)

  def solve(): String = {

    P(0) match {

      case x :: y :: _ if x != y => {

          def row(n: Int): Row = {
            List.range(0, N).map { i =>
              if (i == n || i == N - n - 1) x
              else y
            }
          }

          if (P == List.range(0, N).map(row)) "YES"
          else "NO"
        }
      case _ => "NO"
    }
  }

  out.println(solve)
  out.close
}

import java.util.StringTokenizer

object _404A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (0 until n).map(i => next).toArray
  val ch = a(0)(0)
  val dish = a(0)(1)

  val cb = for {
      i <- 0 until n
      j <- 0 until n
    } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish

  if (cb.forall(i => i)) println("YES")
  else println("NO")
}

import java.util.StringTokenizer

object _404A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (0 until n).map(i => next).toArray
  val ch = a(0)(0)
  val dish = a(0)(1)

  val cb = for {
      i <- 0 until n
      j <- 0 until n
    } yield if (i == j || n - 1 - i == j) a(i)(j) == ch else a(i)(j) == dish

  if (cb != dish && cb.forall(i => i)) println("YES")
  else println("NO")
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val k = in.next().toInt
  val data = Range(0, k).map { i => (i, in.next())}
  val symbols = data.head._2.toSet
  val symbol =  data.head._2.head
  if (symbols.size != 2) println("NO")
  else {
    val r = data.forall{
      case(i, str) =>
        val count = str.count(_ == symbol)
        str.forall(symbols) &&  count < 3 && str.charAt(i) == symbol && str.charAt(str.length - i - 1) == symbol
    }
    if (r)
      println("YES")
    else
      println("NO")
  }

}

object A404 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(read.toCharArray)
    var xChar = in(0)(0)
    var diffChar = in(1)(0)
    var ifX = true
    var ifDiff = true
    for(i <- 0 until n; j <- 0 until n) {
      if(i == j) {// diagonal 1
        ifX &= in(i)(j) == xChar
      } else if(i + j == n-1) {// diagonal 2
        ifX &= in(i)(j) == xChar
      } else {
        ifDiff &= in(i)(j) == diffChar
      }
    }

    if (ifDiff && ifX) {
      println("YES")
    } else {
      println("NO")
    }
  }

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

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

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

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

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

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P404A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  type Row = List[Char]

  val N = sc.nextInt
  sc.nextLine
  val P: List[Row] = List.fill(N)(sc.nextLine.toList)

  def solve(): String = {
    val (x, y) = (P(0)(0), P(0)(1))

    def row(n: Int): Row = {
      List.range(0, N).map { i =>
        if (i == n || i == N - n - 1) x
        else y
      }
    }

    if (P == List.range(0, N).map(row)) "YES"
    else "NO"
  }

  out.println(solve)
  out.close
}


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 = ni()
    val S = ns(N)
    val COLOR = "RGB"

    var best = 1e9.toInt + 10
    var ans: (Int, Int, Int) = null

    def calc(i: Int, j: Int, k: Int): Int = {
      var changed = 0
      val c = Array(i, j, k)
      REP(N) { l =>
        if (S(l) != COLOR(c(l % 3))) changed += 1
      }
      changed
    }

    REP(3) { i =>
      REP(3) { j =>
        REP(3) { k =>
          if (i != j && j != k && i != k) {
            val v = calc(i, j, k)
            if (v < best) {
              best = v
              ans = (i, j, k)
            }
          }
        }
      }
    }

    out.println(best)
    val c = Array(ans._1, ans._2, ans._3)
    REP(N) { i =>
      out.print(COLOR(c(i % 3)))
    }
    out.println()
  }

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

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

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

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

  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[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

//package codeforces.contest1108

/*
http://codeforces.com/contest/1108/problem/C
 */
object NiceGarland {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val str = io.StdIn.readLine()

    val maxZeroes = n / 3 + (if (n % 3 >= 1) 1 else 0)
    val maxOnes = n / 3 + (if (n % 3 == 2) 1 else 0) // 1 2 3, 4 5 6, 7 8 9
    val maxTwos = n / 3

    def count(c: Char): Array[Int] = {
      Array(maxZeroes - (0 until n by 3).count(str(_) == c), maxOnes - (1 until n by 3).count(str(_) == c), maxTwos - (2 until n by 3).count(str(_) == c))
    }

    val redCost = count('R')
    val blueCost = count('B')
    val greenCost = count('G')

    val (optimalPermutation: String, cost: Int) = Set[String]("RGB", "RBG", "BGR", "BRG", "GRB", "GBR")
      .map(s =>
        (s, s.zipWithIndex.foldLeft(0) {
            case (acc: Int, (c: Char, i: Int)) =>
              acc + (c match {
                case 'R' => redCost(i)
                case 'B' => blueCost(i)
                case 'G' => greenCost(i)
              })
          })).minBy(_._2)

    val result = str.toCharArray

    optimalPermutation.zipWithIndex.foreach { case (c, i) => fix(i, c) }

    def fix(startingFrom: Int, withColor: Char): Unit = {
      (startingFrom until n by 3).foreach(result(_) = withColor)
    }

    println(cost + " " + result.mkString(""))
  }
}

object CF_535_3_C {
// date: 25/01/2019

  type In  = (Int, String)
  type Out = String

  def solve(in: In): Out = {
    val (n, s) = in
    // Assume starts with each of R G B
    val cs1 = Vector('R','G','B')
    val cs2 = Vector('R','B','G')
    val ss1 = Stream.iterate(0)(i => (i + 1)%3).map(cs1)
    val ss2 = Stream.iterate(0)(i => (i + 1)%3).map(cs2)

   def differences(xs: Seq[Char], ys: Seq[Char]) = (xs, ys).zipped.count(i => i._1 != i._2)

    val results = for {
      order: Stream[Char] <- Vector(ss1, ss2)
      start <- Seq(order, order.drop(1), order.drop(2))
      seq = start.take(n)
    } yield (seq, differences(seq, s))

    val res = results.minBy(_._2)
    res._2.toString + "\n" +
       res._1.mkString

  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.nextLine})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


import scala.collection._
import scala.collection.mutable.ListBuffer

object HongcowBS2 extends App {

  val tokens = scala.io.Source.stdin.getLines
    .flatMap( _ split ' ' filter (_.nonEmpty))

  def nextInt() = tokens.next().toInt

  def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2

  val n, m, k = nextInt()

  if (k == 1) {
    println(getLinksNum(n) - m)
  } else if (m == 0) {
    println(getLinksNum(n - k + 1))
  } else {

    val governments = (0 until k).map{ _ =>
      val k = nextInt()
      k -> mutable.BitSet(k)
    }.toMap

    var freeLinks = ListBuffer[Array[Int]]()
    for (_ <- 0 until m) {
      val link = Array(nextInt(), nextInt())
      if (governments.contains(link(0))) {
        governments.get(link(0)).get += link(1)
      } else if (governments.contains(link(1))) {
        governments.get(link(1)).get += link(0)
      } else {
        freeLinks += link
      }
    }

    var continue = true
    while (continue) {
      val remainingLinks = ListBuffer[Array[Int]]()
      for (link <- freeLinks) {
        val entry = governments.find { p =>
          (p._2.contains(link(0))
            || p._2.contains(link(1)))
        }
        if (entry.isEmpty) remainingLinks += link
        else entry.get._2 += (link(0), link(1))
      }
      if (remainingLinks.size == freeLinks.size) continue = false
      else freeLinks = remainingLinks
    }

    val govCounts = governments.values.map(_.size).toArray
    val maxIndex = govCounts.indexOf(govCounts.max)
    val freeCount = n - govCounts.sum
    govCounts(maxIndex) = govCounts(maxIndex) + freeCount
    val result = govCounts.map(getLinksNum).sum - m
    println(result)
  }
}

import java.util.StringTokenizer

import scala.collection.mutable

object A extends App {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }

  read()
  val n = st.nextToken().toInt
  val m = st.nextToken().toInt
  val k = st.nextToken().toInt

  read()
  val capitals = Array.fill(k)(st.nextToken().toInt - 1)

  var links = Array.fill(n)(List.empty[Int])
  var a = 0
  var b = 0
  (1 to m).foreach { _ =>
    read()
    a = st.nextToken().toInt - 1
    b = st.nextToken().toInt - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

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

  var stack = new mutable.Stack[Int]
  def count(capital: Int): Int = {
    b = 0
    stack.push(capital)
    while (stack.nonEmpty) {
      a = stack.pop()
      if (!visited(a)) {
        b += 1
        visited(a) = true
        links(a).foreach(stack.push)
      }
    }
    b
  }

  var groups = capitals.map(count)
  val total = groups.sum
  val free = n - total
  val max = groups.max

  def maxForGroup(c: Int) = c * (c-1) / 2

  val maxLinks = groups.map(maxForGroup).sum + maxForGroup(max + free) - maxForGroup(max)
  val ans = maxLinks - m

  println(ans)

}

import scala.collection._
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLine

object HongcowBS extends App {

  def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2

  val Array(n, m, k) = readLine.split(" ").map(_.toInt)

  if (k == 1) {
    println(getLinksNum(n) - m)
  } else if (m == 0) {
    println(getLinksNum(n - k + 1))
  } else {
    val governments = readLine.split(" ").map { e =>
      val k = e.toInt
      k -> mutable.BitSet(k)
    }.toMap

    var freeLinks = ListBuffer[Array[Int]]()
    for (_ <- 0 until m) {
      val link = readLine.split(" ").map(_.toInt)
      val Array(a, b) = link
      if (governments.contains(link(0))) {
        governments.get(link(0)).get += link(1)
      } else if (governments.contains(link(1))) {
        governments.get(link(1)).get += link(0)
      } else {
        freeLinks += link
      }
    }

    var continue = true
    while (continue) {
      val remainingLinks = ListBuffer[Array[Int]]()
      for (link <- freeLinks) {
        val entry = governments.find { p =>
          (p._2.contains(link(0))
            || p._2.contains(link(1)))
        }
        if (entry.isEmpty) remainingLinks += link
        else entry.get._2 += (link(0), link(1))
      }
      if (remainingLinks.size == freeLinks.size) continue = false
      else freeLinks = remainingLinks
    }

    val govCounts = governments.values.map(_.size).toArray
    val maxIndex = govCounts.indexOf(govCounts.max)
    val freeCount = n - govCounts.sum
    govCounts(maxIndex) = govCounts(maxIndex) + freeCount
    val result = govCounts.map(getLinksNum).sum - m
    println(result)
  }
}

import scala.io.StdIn.readLine

object HongCowBuild extends App {

  def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2

  def readLinksAndGetLinkedNodes(m: Int)  = {
    var linkedNodes = 0
    (0 until m).foreach { _ =>
      val Array(s, d) = readLine.split(" ").map(_.toInt)
      if (govNodes.contains(s)) {
        govNodes.put(s, govNodes.get(s).get + 1)
        linkedNodes += 1
      }else if (govNodes.contains(d)){
        govNodes.put(d, govNodes.get(d).get + 1)
        linkedNodes += 1
      }
    }
    linkedNodes
  }

  val Array(n, m, k) = readLine.split(" ").map(_.toInt)
  val governments = readLine.split(" ").map(_.toInt)
  val govNodes = collection.mutable.HashMap[Int, Int]()

  governments.foreach(govNodes.put(_, 1))
  var linkedNodes = readLinksAndGetLinkedNodes(m)
  val maxGov = govNodes.maxBy(_._2)
  val remained = n - k - linkedNodes
  val maxGovSum = getLinksNum(govNodes.remove(maxGov._1).get + remained)
  val allSum = govNodes.map(e => getLinksNum(e._2)).sum
  val result = allSum + maxGovSum - m
  println(result)
}

import scala.io.StdIn.readLine

object Hongcow extends App {

  def getLinksNum(n: Int) = if (n == 1) 0 else n * (n - 1) / 2

  def readLinks(m: Int)  = {
    var freeLinks = 0
    (0 until m).foreach { _ =>
      val Array(s, d) = readLine.split(" ").map(_.toInt)
      if (govNodes.contains(s))
        govNodes.put(s, govNodes.get(s).get + 1)
      else if (govNodes.contains(d))
        govNodes.put(d, govNodes.get(d).get + 1)
      else freeLinks += 1
    }
    freeLinks
  }

  val Array(n, m, k) = readLine.split(" ").map(_.toInt)
  val governments = readLine.split(" ").map(_.toInt)
  val govNodes = collection.mutable.HashMap[Int, Int]()
  governments.foreach(govNodes.put(_, 0))
  var freeLinks = readLinks(m)
  val maxGov = govNodes.maxBy(_._2)
  val maxGovSum = getLinksNum(govNodes.remove(maxGov._2).get)
  val allSum = govNodes.map(e => getLinksNum(e._2)).sum
  val result = allSum + maxGovSum - m
  println(result)
}


import scala.math.BigDecimal.RoundingMode

object Solution {
  val pattern = """(\d+) (\d+) (\d+) (\d+)""".r

  def main(args: Array[String]): Unit = {
    val t = readLine().toLong

    (1L to t)
      .map(i => readLine())
      .map(findSolution)
      .foreach(println)
  }

  def findSolution(line: String): Long = {
    val pattern(x, y, p, q) = line
    val suc = x.toLong
    val total = y.toLong
    val denom = p.toLong
    val numer = q.toLong

    if (denom == 0 && suc == 0)
      0 else
    if (denom == 0 && suc != 0)
      -1 else
    if (denom == numer && suc == total)
      0 else
    if (denom == numer && suc != total)
      -1
    else {
      val k = ((BigDecimal(suc) / denom) setScale(0, RoundingMode.CEILING)).toLong max
        ((BigDecimal(total) / numer) setScale(0, RoundingMode.CEILING)).toLong max
        ((BigDecimal(total - suc) / (numer - denom)) setScale(0, RoundingMode.CEILING)).toLong
      val toSolveSuc = denom * k - suc
      val toSolveUnsuc = numer * k - total - toSolveSuc

      toSolveSuc + toSolveUnsuc
    }
  }
}

//package p807

/**
  * Created by velizar on 16/05/17.
  */
object C extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toLong))
  val Array(t) = input(0)

  val maxValue = 2000000000000000000l

  def search(from: Long, to: Long, x: Long, y: Long, p: Long, q: Long): Long = {
    val current = (from + to) / 2
//    println((from, current, to))
    val currentLB = x
    val currentUB = current * q - y + x
    val currentDesired = current * p
    val inBounds = currentLB <= currentDesired && currentDesired <= currentUB
    if (inBounds && from == to)
      current * q - y
    else if (inBounds)
      search(from, current, x, y, p, q)
    else
      search(current + 1, to, x, y, p, q)
  }

  val output = input.drop(1).map {
    case Array(x, y, p, q) if y % q == 0 && p * (y / q) == x => 0
    case Array(_, _, 0, 1) => -1
    case Array(_, _, 1, 1) => -1
    case Array(x, y, p, q) =>
//      println((x, y, p, q))
      search(y / q + 1, maxValue / q, x, y, p, q)
  }.mkString("\n")
  print(output)
}

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

  val Array(n) = readInts(1)

  for (_ <- 0 until n) {
    val Array(x, y, p, q) = readLongs(4)

    if ((p == q && x < y) || (p == 0 && x > 0)) {
      println(-1)
    } else {

      def can(n: Long): Boolean = {
        val b = q * n - y
        val a = p * n - x
        a >= 0 && a <= b
      }

      @annotation.tailrec
      def binSearch(low: Long, hi: Long): Long = {
        if (hi < low) low
        else {
          val mid = (low + hi) / 2
          if (can(mid)) binSearch(low, mid - 1)
          else binSearch(mid + 1, hi)
        }
      }

      val n = binSearch(1, Int.MaxValue)

      val b = q * n - y

      println(b)
    }
  }
}

//package p807

/**
  * Created by velizar on 16/05/17.
  */
object C extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(t) = input(0)

//  def succ(x: Int, y: Int) = x
//  def failed(x: Int, y: Int) = y - x

  def search(from: Int, to: Int, x: Int, y: Int, p: Int, q: Int): Int = {
    val currentD = (from + to) / 2.0
    val current = (if (scala.util.Random.nextBoolean()) currentD.floor else currentD.ceil).toInt
    val currentLB = x
    val currentUB = current * q - y + x
    val currentDesired = current * p
    val inBounds = currentLB <= currentDesired && currentDesired <= currentUB
    if (inBounds && from == to)
      current * q - y
    else if (inBounds)
      search(from, current, x, y, p, q)
    else
      search(current + 1, to, x, y, p, q)
  }

  val maxValue = 2000000000
  def solve(x: Int, y: Int, p: Int, q: Int): Int = {
    if (y % q == 0 && p * (y / q) == x)
      0
    else
      search(y / q + 1, maxValue / q, x, y, p, q)
  }

  val output = input.drop(1).map {
    case Array(_, _, 0, 1) => -1
    case Array(_, _, 1, 1) => -1
    case Array(x, y, p, q) => solve(x, y, p, q)
  }.mkString("\n")
  print(output)
}

//package p807

/**
  * Created by velizar on 16/05/17.
  */
object C extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(t) = input(0)

//  def succ(x: Int, y: Int) = x
//  def failed(x: Int, y: Int) = y - x

  def search(from: Int, to: Int, x: Int, y: Int, p: Int, q: Int): Int = {
    val currentD = (from + to) / 2.0
    val current = (if (scala.util.Random.nextBoolean()) currentD.floor else currentD.ceil).toInt
    val currentLB = x
    val currentUB = current * q - y + x
    val currentDesired = current * p
    val inBounds = currentLB <= currentDesired && currentDesired <= currentUB
    if (inBounds && from == to)
      current * q - y
    else if (inBounds)
      search(from, current, x, y, p, q)
    else
      search(current + 1, to, x, y, p, q)
  }

  val maxValue = 2000000000
  def solve(x: Int, y: Int, p: Int, q: Int): Int = {
    if (y % q == 0 && p * (y / q) == x)
      0
    else
      search(y / q + 1, maxValue / q, x, y, p, q)
  }

  val output = input.drop(1).map {
    case Array(x, y, p, q) if x == p && y == q => 0
    case Array(_, _, 0, 1) => -1
    case Array(_, _, 1, 1) => -1
    case Array(x, y, p, q) => solve(x, y, p, q)
  }.mkString("\n")
  print(output)
}


import java.io._
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new BufferedReader(new java.io.InputStreamReader(System.in))
    val writer =  new PrintWriter(System.out)
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readString().split("").map(_.toInt)
        val b = readString().split("").map(_.toInt)

        var count = 0
        for (i <- 0 until n) {
            if (a(i) == 0) {
                if (b(i) == 1) {
                    count += 1
                    b(i) = 0
                }
            } else {
                if (i - 1 >= 0 && b(i - 1) == 1)
                    count += 1
                else if (i + 1 < n && b(i + 1) == 1) {
                    count += 1
                    b(i + 1) = 0
                }
            }
        }

        writer.println(count)

    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (1, 1))   => (count + 2, 0, 0)
      case ((count, 1, 1), (1, 0))   => (count + 1, 0, 0)
      case ((count, 1, 0), (1, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (0, 1))   => (count + 1, 0, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (tm, bm) = (tn zip bn).map {
      case (0, 1) => (1, 0)
      case (t, b) => (t, b)
    }.unzip

    val (ans, _, _) = (tm zip bm).foldLeft((tm.count(_ == 1) - tn.count(_ == 1), 0, 0)) {
      case ((c, 1, 1), (1, 1)) => (c + 2, 1, 0)
      case ((c, 1, 1), (1, 0)) => (c + 1, 1, 0)
      case ((c, 1, 0), (1, 1)) => (c + 1, 1, 0)
      case ((c, _, _), (x, y)) => (c, x, y)
    }

    println(ans)

  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (1, 1)) => (count + 2, 1, 0)
      case ((count, 1, 1), (1, 0)) => (count + 1, 1, 0)
      case ((count, 1, 1), (0, 1)) => (count + 2, 1, 0)
      case ((count, 1, 1), (0, 0)) => (count, 0, 0)

      case ((count, 1, 0), (1, 1)) => (count + 1, 1, 0)
      case ((count, 1, 0), (1, 0)) => (count, 1, 0)
      case ((count, 1, 0), (0, 1)) => (count + 1, 1, 0)
      case ((count, 1, 0), (0, 0)) => (count, 0, 0)

      case ((count, _, _), (0, 1)) => (count + 1, 1, 0)

      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, 1, 1), (1, _))   => (count + 1, 1, 0)
      case ((count, 1, 0), (_, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, 1, 0), (_, 1))   => (count + 1, 1, 0)
      case ((count, 0, 0), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, 1, _), (1, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, _, _), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)
    }

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val tn = readLine().split("").map(_.toInt)
    val bn = readLine().split("").map(_.toInt)

    val (ans, _, _) = (tn zip bn).foldLeft((0, 0, 0)) {
      case ((count, 1, 1), (_, 1))   => (count + 2, 1, 0)
      case ((count, 1, _), (ti, 1))  => (count + 1, ti, 0)
      case ((count, _, 1), (1, bi))  => (count + 1, 1, bi)
      case ((count, _, _), (0, 1))   => (count + 1, 1, 0)
      case ((count, _, _), (ti, bi)) => (count, ti, bi)

    }

    println(ans)
  }
}