An array $$$[b_1, b_2, \ldots, b_m]$$$ is a palindrome, if $$$b_i = b_{m+1-i}$$$ for each $$$i$$$ from $$$1$$$ to $$$m$$$. Empty array is also a palindrome.An array is called kalindrome, if the following condition holds: It's possible to select some integer $$$x$$$ and delete some of the elements of the array equal to $$$x$$$, so that the remaining array (after gluing together the remaining parts) is a palindrome. Note that you don't have to delete all elements equal to $$$x$$$, and you don't have to delete at least one element equal to $$$x$$$.For example :   $$$[1, 2, 1]$$$ is kalindrome because you can simply not delete a single element.  $$$[3, 1, 2, 3, 1]$$$ is kalindrome because you can choose $$$x = 3$$$ and delete both elements equal to $$$3$$$, obtaining array $$$[1, 2, 1]$$$, which is a palindrome.  $$$[1, 2, 3]$$$ is not kalindrome. You are given an array $$$[a_1, a_2, \ldots, a_n]$$$. Determine if $$$a$$$ is kalindrome or not.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the array. It's guaranteed that the sum of $$$n$$$ over all test cases won't exceed $$$2 \cdot 10^5$$$.

For each test case, print YES if $$$a$$$ is kalindrome and NO otherwise. You can print each letter in any case.

NoteIn the first test case, array $$$[1]$$$ is already a palindrome, so it's a kalindrome as well.In the second test case, we can choose $$$x = 2$$$, delete the second element, and obtain array $$$[1]$$$, which is a palindrome.In the third test case, it's impossible to obtain a palindrome.In the fourth test case, you can choose $$$x = 4$$$ and delete the fifth element, obtaining $$$[1, 4, 4, 1]$$$. You also can choose $$$x = 1$$$, delete the first and the fourth elements, and obtain $$$[4, 4, 4]$$$.

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main2 extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b:  Int, c: Double)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (b == that.b)
                return -1 * c.compareTo(that.c)
            else
                return -1 * b.compareTo(that.b)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n+2)
        for (i <- 1 to n) {
            arr(i) = readInt()
        }
        var pal = false
        var ig1 = arr(0)
        var ig2 = arr(0)
        for (i <- n/2 to n) {
            if (arr(i) != arr(n-i+1)) {
                ig1 = arr(i)
                ig2 = arr(n-i+1)
            }
        }
        def check(ig: Int): Boolean = {
            var l = 1
            var r = n
            while (l <= r) {
                while (l <= n && arr(l) == ig) {
                    l += 1
                }
                while (r >= 1 && arr(r) == ig) {
                    r -= 1
                }
                if (l > n || r < 1) {
                    if (l > n && r < 1)
                        return true
                    else
                        return false
                }
                if (arr(l) != arr(r))
                    return false
                l += 1
                r -= 1
            }
            return true
        }
        if (check(ig1) || check(ig2))
            writer.println("YES")
        else
            writer.println("NO")
    }
    writer.flush()
}

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main2 extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b:  Int, c: Double)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            if (b == that.b)
                return -1 * c.compareTo(that.c)
            else
                return -1 * b.compareTo(that.b)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n+2)
        for (i <- 1 to n) {
            arr(i) = readInt()
        }
        var pal = false
        var ig1 = arr(0)
        var ig2 = arr(0)
        for (i <- 1 to n/2) {
            if (arr(i) != arr(n-i+1)) {
                ig1 = arr(i)
                ig2 = arr(n-i+1)
            }
        }
        def check(ig: Int): Boolean = {
            var l = 1
            var r = n
            while (l < r) {
                while (l <= n && arr(l) == ig) {
                    l += 1
                }
                while (r >= 1 && arr(r) == ig) {
                    r -= 1
                }
                if (l > n || r < 1)
                    return true
                if (arr(l) != arr(r))
                    return false
                l += 1
                r -= 1
            }
            return true
        }
        if (check(ig1) || check(ig2))
            writer.println("YES")
        else
            writer.println("NO")
    }
    writer.flush()
}


One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.A contest has just finished. There are n teams, numbered 1 through n. The i-th team has ti balloons and weight wi. It's guaranteed that ti doesn't exceed wi so nobody floats initially.Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.What is the best place Limak can get?

The first line of the standard input contains one integer n (2 ≤ n ≤ 300 000) — the number of teams. The i-th of n following lines contains two integers ti and wi (0 ≤ ti ≤ wi ≤ 1018) — respectively the number of balloons and the weight of the i-th team. Limak is a member of the first team.

Print one integer denoting the best place Limak can get.

NoteIn the first sample, Limak has 20 balloons initially. There are three teams with more balloons (32, 40 and 45 balloons), so Limak has the fourth place initially. One optimal strategy is: Limak gives 6 balloons away to a team with 32 balloons and weight 37, which is just enough to make them fly. Unfortunately, Limak has only 14 balloons now and he would get the fifth place. Limak gives 6 balloons away to a team with 45 balloons. Now they have 51 balloons and weight 50 so they fly and get disqualified. Limak gives 1 balloon to each of two teams with 16 balloons initially. Limak has 20 - 6 - 6 - 1 - 1 = 6 balloons. There are three other teams left and their numbers of balloons are 40, 14 and 2. Limak gets the third place because there are two teams with more balloons. In the second sample, Limak has the second place and he can't improve it.In the third sample, Limak has just enough balloons to get rid of teams 2, 3 and 5 (the teams with 81 000 000 000, 5 000 000 000 and 46 000 000 000 balloons respectively). With zero balloons left, he will get the second place (ex-aequo with team 6 and team 7).

import scala.collection.mutable

object D extends App {

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

  val Array(n) = readInts(1)

  val teams = Array.ofDim[Team](n - 1)

  val Array(_t0, w0) = readLongs(2)
  var t0 = _t0

  case class Team(t: Long, w: Long)

  for (i <- 0 until n - 1) {
    val Array(t, w) = readLongs(2)
    teams(i) = Team(t, w)
  }

  val above = mutable.PriorityQueue.empty[Team](Ordering.by(t => - (t.w - t.t)))
  val below = mutable.PriorityQueue.empty[Team](Ordering.by(_.t))

  for (t <- teams) if (t.t > t0) above += t
  else below += t

  var minPlace = above.size + 1
  var can = true

  while (can && !above.isEmpty) {
    val target = above.dequeue()
    if (target.w - target.t < t0) {
      t0 -= target.w - target.t + 1
      while (below.nonEmpty && below.head.t > t0) {
        above += below.dequeue()
      }
      minPlace = Math.min(minPlace, above.size + 1)
    } else can = false
  }

  println(minPlace)
}

object CF{
	import scala.io.StdIn.{readInt, readLine}
	import scala.collection.mutable.PriorityQueue
	import math.{max, min}

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

		val datasq = PriorityQueue.empty[(Long, Long)](Ordering.by((_:(Long, Long))._1))
		var (mdatat, mdataw) = {
			val line = readLine().split(" ").map(_.toLong)
			(line(0), line(1))
		}
		for(_ <- 1 to n-1) datasq += {
			val line = readLine().split(" ").map(_.toLong)
			(line(0), line(1))
		}

		val queue = PriorityQueue.empty[Long](Ordering.by((x:Long) => x).reverse)
		makeQueue(queue, datasq, mdatat)
		val cur = queue.length + 1
		var best = cur

		while(!queue.isEmpty && mdatat >= 0){
			val head = queue.dequeue()
			mdatat -= head

			if(mdatat >= 0){
				while(!datasq.isEmpty && datasq.head._1 > mdatat){
					val head = datasq.dequeue()
					queue += head._2 - head._1 + 1
				}
				best = min(best, queue.length + 1)
			}
		}
		println(best)
	}

	def makeQueue(q: PriorityQueue[Long], datasq:PriorityQueue[(Long, Long)], mdatat: Long){
		if(datasq.isEmpty) return
		if(datasq.head._1 > mdatat){
			val head = datasq.dequeue()
			q += head._2 - head._1 + 1
			makeQueue(q, datasq, mdatat)
		}
	}
}

object CF{
	import scala.io.StdIn.{readInt, readLine}
	import scala.collection.mutable.PriorityQueue

	def main(args: Array[String]){
		val n = readInt()
		val datasq = PriorityQueue.empty[Node](Ordering.by((_:Node).t))
		val mdata = {
			val line = readLine().split(" ").map(_.toLong)
			new Node(line(0), line(1))
		}
		for(_ <- 1 to n-1) datasq += {
			val line = readLine().split(" ").map(_.toLong)
			new Node(line(0), line(1))
		}
		val datas = pq2list(datasq)
		val queue = PriorityQueue.empty[Node](Ordering.by((_:Node).h).reverse)
		var i = 0
		while(i<datas.length && datas(i).t > mdata.t){
			queue += datas(i)
			i += 1
		}

		var best = queue.length+1
		var now = best
		var cur = best

		while(!queue.isEmpty && mdata.t>=0){
			val head = queue.dequeue()
			mdata.t -= head.h
			if(mdata.t >= 0){
				now -= 1
				var i = cur
				while(i<datas.length && datas(i).t > mdata.t){
					queue += datas(i)
					now += 1
					cur += 1
					i += 1
				}
				if(now<best) best=now;
				//println(queue)
				//println(best)
			}
		}
		println(best)
	}

	def pq2list(pq: PriorityQueue[Node]): List[Node] = {
		if(pq.isEmpty) return Nil
		return pq.head :: pq2list(pq.drop(1))
	}

	class Node(var t:Long, val w:Long){
		val h: Long = w-t

		override def toString():String = {
			f"[Node t:$t w:$w, h:$h]"
		}
	}
}

object CF{
	import scala.io.StdIn.{readInt, readLine}
	import scala.collection.mutable.PriorityQueue

	def main(args: Array[String]){
		val n = readInt()
		val datasq = PriorityQueue.empty[Node](Ordering.by((_:Node).t))
		val mdata = {
			val line = readLine().split(" ").map(_.toLong)
			new Node(line(0), line(1))
		}
		for(_ <- 1 to n-1) datasq += {
			val line = readLine().split(" ").map(_.toLong)
			new Node(line(0), line(1))
		}
		val datas = pq2list(datasq)
		val queue = PriorityQueue.empty[Node](Ordering.by((_:Node).h).reverse)
		var i = 0
		while(i<datas.length && datas(i).t > mdata.t){
			queue += datas(i)
			i += 1
		}

		var best = queue.length+1
		var now = best
		var cur = best

		while(!queue.isEmpty && mdata.t>=0){
			val head = queue.dequeue()
			now -= 1
			mdata.t -= head.h
			if(mdata.t >= 0){
				while(cur<datas.length && datas(cur).t > mdata.t){
					queue += datas(i)
					now += 1
					cur += 1
				}
				if(now<best) best=now;

			}
		}
		println(best)
	}

	def pq2list(pq: PriorityQueue[Node]): List[Node] = {
		if(pq.isEmpty) return Nil
		return pq.head :: pq2list(pq.drop(1))
	}

	class Node(var t:Long, val w:Long){
		val h: Long = w-t+1

		override def toString():String = {
			f"[Node t:$t w:$w, h:$h]"
		}
	}
}

object CF{
	import scala.io.StdIn.{readInt, readLine}
	import scala.collection.mutable.PriorityQueue
	import math.max

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

		val datasq = PriorityQueue.empty[Node](Ordering.by((_:Node).t))
		val mdata = {
			val line = readLine().split(" ").map(_.toLong)
			new Node(line(0), line(1))
		}
		for(_ <- 1 to n-1) datasq += {
			val line = readLine().split(" ").map(_.toLong)
			new Node(line(0), line(1))
		}

		val queue = PriorityQueue.empty[Node](Ordering.by((_:Node).h).reverse)
		var cur = makeQueue(queue, datasq, mdata) + 1
		var best = cur

		while(!queue.isEmpty && mdata.t >= 0){
			val head = queue.dequeue()
			mdata.t -= head.h

			if(mdata.t >= 0){
				while(!datasq.isEmpty && datasq.head.t > mdata.t){
					queue += datasq.dequeue()
				}
				best = max(best, queue.length + 1)
			}
		}
		println(best)
	}

	def makeQueue(q: PriorityQueue[Node], datasq:PriorityQueue[Node], mdata: Node):Long = {
		if(datasq.isEmpty) return 0
		if(datasq.head.t > mdata.t) {
			q += datasq.dequeue()
			return 1 + makeQueue(q, datasq, mdata)
		}
		return 0
	}

	class Node(var t:Long, val w:Long){
		val h:Long = w-t+1
	}
}


During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string $$$c$$$ consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).Katie has a favorite string $$$s$$$ and a not-so-favorite string $$$t$$$ and she would love to recover the mysterious code so that it has as many occurrences of $$$s$$$ as possible and as little occurrences of $$$t$$$ as possible. Formally, let's denote $$$f(x, y)$$$ as the number of occurrences of $$$y$$$ in $$$x$$$ (for example, $$$f(aababa, ab) = 2$$$). Katie wants to recover the code $$$c'$$$ conforming to the original $$$c$$$, such that $$$f(c', s) - f(c', t)$$$ is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out.

The first line contains string $$$c$$$ ($$$1 \leq |c| \leq 1000$$$) — the mysterious code . It is guaranteed that $$$c$$$ consists of lowercase English characters and asterisks "*" only. The second and third line contain strings $$$s$$$ and $$$t$$$ respectively ($$$1 \leq |s|, |t| \leq 50$$$, $$$s \neq t$$$). It is guaranteed that $$$s$$$ and $$$t$$$ consist of lowercase English characters only.

Print a single integer — the largest possible value of $$$f(c', s) - f(c', t)$$$ of the recovered code.

NoteIn the first example, for $$$c'$$$ equal to "katie" $$$f(c', s) = 1$$$ and $$$f(c', t) = 0$$$, which makes $$$f(c', s) - f(c', t) = 1$$$ which is the largest possible.In the second example, the only $$$c'$$$ conforming to the given $$$c$$$ is "caat". The corresponding $$$f(c', s) - f(c', t) = 1 - 2 = -1$$$.In the third example, there are multiple ways to recover the code such that $$$f(c', s) - f(c', t)$$$ is largest possible, for example "aaa", "aac", or even "zaz". The value of $$$f(c', s) - f(c', t) = 0$$$ for all of these recovered codes.In the fourth example, the optimal recovered code $$$c'$$$ would be "ccc". The corresponding $$$f(c', s) - f(c', t) = 2$$$.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val C, S, T = ns()

    val dp = Array.fill[Int](C.length + 1, S.length, T.length)(-1e5.toInt)
    dp(0)(0)(0) = 0
    val kmpS = new KMP(S)
    val kmpT = new KMP(T)

    def step(i: Int, c: Char): Unit = {
      REP(S.length) { j =>
        REP(T.length) { k =>
          var nextS = kmpS.longestSuffix(j, c)
          var nextT = kmpT.longestSuffix(k, c)
          var diff = 0
          if (nextS == S.length) {
            diff += 1
            nextS = kmpS.kmp.last
          }
          if (nextT == T.length) {
            diff -= 1
            nextT = kmpT.kmp.last
          }
          dp(i + 1)(nextS)(nextT) = max(dp(i + 1)(nextS)(nextT), dp(i)(j)(k) + diff)
        }
      }
    }

    REP(C.length) { i =>
      if (C(i) != '*') {
        step(i, C(i))
      } else {
        REP(26) { j =>
          step(i, ('a' + j).toChar)
        }
      }
      debug(s"DP($i)")
      debugDim(dp(i + 1))
    }

    val ans = dp(C.length).map(_.max).max
    out.println(ans)
  }

  class KMP(word: String) {
    val kmp: Array[Int] = Array.ofDim[Int](word.length + 1)
    2 to word.length foreach { i =>
      // kmp(i-1)以下しか参照されないからOK
      kmp(i) = longestSuffix(kmp(i - 1), word(i - 1))
    }

    def findFirst(text: String): Int = {
      var j = 0
      REP(text.length) { i =>
        j = longestSuffix(j, text(i))
        if (j == word.length) return i - word.length + 1
      }
      -1
    }

    def longestSuffix(matched: Int, c: Char): Int = {
      var j = matched
      var continues = true
      while(continues) {
        if (j < word.length && word(j) == c) {
          j += 1
          continues = false
        } else if (j == 0) continues = false
        else j = kmp(j)
      }
      j
    }
  }

}


Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries:  "+ x" — add integer x to multiset A. "- x" — erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. "? x" — you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.

The first line of the input contains a single integer q (1 ≤ q ≤ 200 000) — the number of queries Vasiliy has to perform. Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1 ≤ xi ≤ 109). It's guaranteed that there is at least one query of the third type. Note, that the integer 0 will always be present in the set A.

For each query of the type '?' print one integer — the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.

NoteAfter first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1.The answer for the sixth query is integer  — maximum among integers , , ,  and .

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

object Multiset extends App {

  implicit class RichInt(val v: Int) {
    def bits: Seq[Byte] = for (x <- 0 to 30) yield (1 & v >> (30 - x)).toByte

  }

  sealed trait Tree

  case class Node(zero: Tree, one: Tree) extends Tree

  case object Empty extends Tree

  case class Leaf(var count: Int, val num: Int) extends Tree

  implicit class TreeOps(t: Tree) {
    def add(v: Int): Tree = {
      def add(t: Tree, bits: Seq[Byte]): Tree = t match {
        case Leaf(x, num) => Leaf(x + 1, num)
        case Empty if bits.isEmpty => Leaf(1, v)
        case Empty => add(Node(Empty, Empty), bits)
        case Node(zero, one) => if (bits.head > 0) Node(zero, add(one, bits.tail))
        else Node(add(zero, bits.tail), one)
      }

      add(t, v.bits)
    }

    def maxXor(v: Int): Int = {
      def max(t: Tree, bits: Seq[Byte]): Int = t match {
        case Empty => v
        case Leaf(_, num) => v ^ num
        case Node(zero, Empty) => max(zero, bits.tail)
        case Node(Empty, one) => max(one, bits.tail)
        case Node(zero, one) => if (bits.head == 0) max(one, bits.tail) else max(zero, bits.tail)
      }

      max(t, v.bits)
    }

    def remove(v: Int): Tree = {
      def remove(t: Tree, bits: Seq[Byte]): Tree = t match {
        case Leaf(1, v) => Empty
        case Leaf(n, v) => Leaf(n - 1, v)
        case Empty => Empty
        case Node(zero, one) => {
          val result = if (bits.head > 0) Node(zero, remove(one, bits.tail))
          else Node(remove(zero, bits.tail), one)
          if (result.one == Empty && result.zero == Empty) Empty
          else result
        }
      }

      remove(t, v.bits)
    }

  }

  var t: Tree = Empty.add(0)
  val numOfEntrees = StdIn.readLine().toInt
  val result: ArrayBuffer[String] = ArrayBuffer()
  for (x <- 1 to numOfEntrees) {
    val data = StdIn.readLine().split(" ")
    val command = data.head
    val value = data.tail.head.toInt
    command match {
      case "+" => t = t.add(value)
      case "-" => t = t.remove(value)
      case "?" => result.append(s"${t.maxXor(value)}")
    }
  }
  result.foreach(println)
}

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

object Multiset extends App {

  implicit class RichInt(val v: Int) {
    def bits: Seq[Byte] = for (x <- 0 to 30) yield (1 & v >> (30 - x)).toByte

  }

  sealed trait Tree

  case class Node(zero: Tree, one: Tree) extends Tree

  case object Empty extends Tree

  case class Leaf(var count: Int, val num: Int) extends Tree

  implicit class TreeOps(t: Tree) {
    def add(v: Int): Tree = {
      def add(t: Tree, bits: Seq[Byte]): Tree = t match {
        case Leaf(x, num) => Leaf(x + 1, num)
        case Empty if bits.isEmpty => Leaf(1, v)
        case Empty => add(Node(Empty, Empty), bits)
        case Node(zero, one) => if (bits.head > 0) Node(zero, add(one, bits.tail))
        else Node(add(zero, bits.tail), one)
      }

      add(t, v.bits)
    }

    def maxXor(v: Int): Int = {
      def max(t: Tree, bits: Seq[Byte]): Int = t match {
        case Empty => v
        case Leaf(_, num) => v ^ num
        case Node(zero, Empty) => max(zero, bits.tail)
        case Node(Empty, one) => max(one, bits.tail)
        case Node(zero, one) => if (bits.head == 0) max(one, bits.tail) else max(zero, bits.tail)
      }

      max(t, v.bits)
    }

    def remove(v: Int): Tree = {
      def remove(t: Tree, bits: Seq[Byte]): Tree = t match {
        case Leaf(1, v) => Empty
        case Leaf(n, v) => Leaf(n - 1, v)
        case Empty => Empty
        case Node(zero, one) => {
          val result = if (bits.head > 0) Node(zero, remove(one, bits.tail))
          else Node(remove(zero, bits.tail), one)
          if (result.one == Empty && result.zero == Empty) Empty
          else result
        }
      }

      remove(t, v.bits)
    }

  }

  var t: Tree = Empty
  val numOfEntrees = StdIn.readLine().toInt
  val result: ArrayBuffer[String] = ArrayBuffer()
  for (x <- 1 to numOfEntrees) {
    val data = StdIn.readLine().split(" ")
    val command = data.head
    val value = data.tail.head.toInt
    command match {
      case "+" => t = t.add(value)
      case "-" => t = t.remove(value)
      case "?" => result.append(s"${t.maxXor(value)}")
    }
  }
  result.foreach(println)
}


Valera considers a number beautiful, if it equals 2k or -2k for some integer k (k ≥ 0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number n into beautiful summands, you need to find the size of the decomposition which has the fewest summands.

The first line contains string s (1 ≤ |s| ≤ 106), that is the binary representation of number n without leading zeroes (n > 0).

Print a single integer — the minimum amount of beautiful numbers that give a total of n.

NoteIn the first sample n = 2 is a beautiful number.In the second sample n = 7 and Valera can decompose it into sum 23 + ( - 20).In the third sample n = 109 can be decomposed into the sum of four summands as follows: 27 + ( - 24) + ( - 22) + 20.

object probE extends App{
   val arr = readLine()
   var ones = 0
   var x = 0
   var oc = 0
   for(i <- arr.length-1 to 0 by -1){
      if(arr(i)=='0'){
         if(oc==1){
            x+=1
            oc=0
         }
         else if(oc>1){
            oc = 1
            x+=1
         }
      }
      else{
         ones+=1
         oc+=1
      }
   }
   var ad = 2
   if(oc==1) ad=1
   println(math.min(x+ad,ones))
}

object probE extends App{
   val arr = readLine()
   var ones = 0
   var x = 0
   var oc = 0
   for(i <- arr.length-1 to 0 by -1){
      if(arr(i)=='0'){
         if(oc==1){
            x+=1
            oc=0
         }
         else {
            oc = 1
            x+=1
         }
      }
      else{
         ones+=1
         oc+=1
      }
   }
   var ad = 2
   if(oc==1) ad=1
   println(math.min(x+ad,ones))
}


Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $$$n$$$ integers, now it's time to distribute them between his friends rationally...Lee has $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ in his backpack and he has $$$k$$$ friends. Lee would like to distribute all integers in his backpack between his friends, such that the $$$i$$$-th friend will get exactly $$$w_i$$$ integers and each integer will be handed over to exactly one friend.Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get.Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$3t$$$ lines contain test cases — one per three lines. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le n$$$) — the number of integers Lee has and the number of Lee's friends. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the integers Lee has. The third line contains $$$k$$$ integers $$$w_1, w_2, \ldots, w_k$$$ ($$$1 \le w_i \le n$$$; $$$w_1 + w_2 + \ldots + w_k = n$$$) — the number of integers Lee wants to give to each friend.  It's guaranteed that the sum of $$$n$$$ over test cases is less than or equal to $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum sum of happiness Lee can achieve.

NoteIn the first test case, Lee should give the greatest integer to the first friend (his happiness will be $$$17 + 17$$$) and remaining integers to the second friend (his happiness will be $$$13 + 1$$$).In the second test case, Lee should give $$$\{10, 10, 11\}$$$ to the first friend and to the second friend, so the total happiness will be equal to $$$(11 + 10) + (11 + 10)$$$In the third test case, Lee has four friends and four integers, it doesn't matter how he distributes the integers between his friends.

import java.util.StringTokenizer

import scala.io.StdIn

object Main {
  object Scanner {
    private var st: StringTokenizer = _

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

    def nextInt: Int = nextToken().toInt
    def nextLong: Long = nextToken().toLong
    def nextShort: Short = nextToken().toShort
    def nextByte: Byte = nextToken().toByte
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to Scanner.nextInt) {
      val n = Scanner.nextInt
      val k = Scanner.nextInt
      val as = new Array[Int](n)
      for (i <- 0 until n) {
        as(i) = Scanner.nextInt
      }
      val ass = as.sorted
      val ws = new Array[Int](k)
      for (i <- 0 until k) {
        ws(i) = Scanner.nextInt
      }
      val wss = ws.sorted
      var sum = 0L
      var cur = n - k
      for (i <- 0 until k) {
        sum += ass(n - i - 1) + (if (wss(i) == 1) ass(n - i - 1) else ass(cur - wss(i) + 1))
        cur -= wss(i) - 1
      }
      println(sum)
    }
  }
}

import java.util.StringTokenizer

import scala.io.StdIn

object Main {
  object Scanner {
    private var st: StringTokenizer = _

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

    def nextInt: Int = nextToken().toInt
    def nextLong: Long = nextToken().toLong
    def nextShort: Short = nextToken().toShort
    def nextByte: Byte = nextToken().toByte
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to Scanner.nextInt) {
      val n = Scanner.nextInt
      val k = Scanner.nextInt
      val as = new Array[Int](n)
      for (i <- 0 until n) {
        as(i) = Scanner.nextInt
      }
      val ass = as.sorted
      val ws = new Array[Int](k)
      for (i <- 0 until k) {
        ws(i) = Scanner.nextInt
      }
      val wss = ws.sorted
      var sum = 0L
      var cur = 0
      for (i <- wss) {
        sum += ass(n - cur - 1) + ass(n - cur - i)
        cur += i
      }
      println(sum)
    }
  }
}


You are given an array $$$a_1, a_2, \dots , a_n$$$ consisting of integers from $$$0$$$ to $$$9$$$. A subarray $$$a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$$$ is good if the sum of elements of this subarray is equal to the length of this subarray ($$$\sum\limits_{i=l}^{r} a_i = r - l + 1$$$).For example, if $$$a = [1, 2, 0]$$$, then there are $$$3$$$ good subarrays: $$$a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$$$ and $$$a_{1 \dots 3} = [1, 2, 0]$$$.Calculate the number of good subarrays of the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains a string consisting of $$$n$$$ decimal digits, where the $$$i$$$-th digit is equal to the value of $$$a_i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the number of good subarrays of the array $$$a$$$.

NoteThe first test case is considered in the statement.In the second test case, there are $$$6$$$ good subarrays: $$$a_{1 \dots 1}$$$, $$$a_{2 \dots 2}$$$, $$$a_{1 \dots 2}$$$, $$$a_{4 \dots 4}$$$, $$$a_{5 \dots 5}$$$ and $$$a_{4 \dots 5}$$$. In the third test case there is only one good subarray: $$$a_{2 \dots 6}$$$.

object C extends App {
  import scala.io.StdIn._
  import scala.collection.immutable.HashMap

  val t = readInt()

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

    val ans = an
      .map(_ - 1)
      .foldLeft((0L, 0L, HashMap(0L -> 1))) { // prefix_sum(0) = 0  -->  counts(0) = 1
        case ((answer, prefix, counts), a) =>
          val key = prefix + a
          val add = counts.getOrElse(key, 0) //

          (answer + add, key, counts + (key -> (add + 1)))
      }
      ._1

    println(ans)
  }
}

import scala.collection.mutable.Map
object C extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val _         = in.nextInt()
      val intInputs = in.line().split("").map(x => x.toInt - 1)

      val map1: Map[Int, Int] = Map.empty[Int, Int]
//      val map1: Map[Int, Int] = Map((0, 1))

      val targetSum    = 0
      var result: Long = 0L
      var cumSum       = 0
      intInputs.foreach(x => {
        /*cumSum += x
        result += map1.getOrElse(cumSum - targetSum, 0)
        map1.put(cumSum, map1.getOrElse(cumSum, 0) + 1)
         */

        cumSum += x
        if (cumSum == targetSum) result += 1
        val rest = cumSum - targetSum
        result += map1.getOrElse(rest, 0)

        map1.put(cumSum, map1.getOrElse(cumSum, 0) + 1)
      })
      println(result)
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

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

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object C extends App {
  import scala.io.StdIn._
  import scala.collection.immutable.HashMap

  val t = readInt()

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

    val ans = an
      .map(_ - 1)
      .foldLeft((0, 0, HashMap(0 -> 1))) { // prefix_sum(0) = 0  -->  counts(0) = 1
        case ((answer, prefix, counts), a) =>
          val key = prefix + a
          val add = counts.getOrElse(key, 0) //

          (answer + add, key, counts + (key -> (add + 1)))
      }
      ._1

    println(ans)
  }
}

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

  val t = readInt()

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

    @annotation.tailrec
    def go(iter: Int, count: Int): Int =
      if (iter > n || iter > 9) count
      else go(iter + 1, count + an.sliding(iter).count(_.sum == iter))

    val ans = go(1, 0)

    println(ans)
  }
}

import scala.collection.mutable.Map
object C extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val _         = in.nextInt()
      val intInputs = in.line().split("").map(x => x.toInt - 1)

      val map1: Map[Int, Int] = Map.empty[Int, Int]
//      val map1: Map[Int, Int] = Map((0, 1))

      val targetSum = 0
      var result    = 0
      var cumSum    = 0
      intInputs.foreach(x => {
        /*cumSum += x
        result += map1.getOrElse(cumSum - targetSum, 0)
        map1.put(cumSum, map1.getOrElse(cumSum, 0) + 1)
        */

        cumSum += x
        if(cumSum == targetSum) result += 1
        val rest = cumSum - targetSum
        result += map1.getOrElse(rest, 0)

        map1.put(cumSum, map1.getOrElse(cumSum, 0) + 1)
      })
      println(result)
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

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

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}


Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:  there wouldn't be a pair of any side-adjacent cards with zeroes in a row;  there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.

The first line contains two integers: n (1 ≤ n ≤ 106) — the number of cards containing number 0; m (1 ≤ m ≤ 106) — the number of cards containing number 1.

In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  var Array(n0, m1) = in.next().split(' ').map(_.toInt)
  val res = Array.ofDim[Int](n0 + m1)
  var solution = true
  (0 until n0 + m1).foreach{
    case el if !solution =>
    case el if el > 0 && res(el - 1) == 0 =>
      res(el) = 1
      m1 -= 1
      solution &&= m1 >= 0
    case el if el > 1 && (res(el - 1) == res(el - 2) && res(el - 1) == 1) || n0 > m1 =>
      res(el) = 0
      n0 -= 1
      solution &&= n0 >= 0
    case el =>
      res(el) = 1
      m1 -= 1
      solution &&= m1 >= 0
  }
  if (!solution)
    println(-1)
  else
    println(res.mkString)
}

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

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

object C401 {

  var result = true
  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)

  def solve: Int = {
    var n = nextInt
    var m = nextInt
    if (n > m + 1)
      out.println(-1)
    else if (n == m + 1) {
      for (i <- 0 until (n + m - 1) / 2) {
        out.print("01")
      }
      out.println("0")
    } else if (m > 2 * n + 2) {
      out.println(-1)
    } else {
      val sb = new StringBuilder()
      while (n != m && n > 0 && m > 0 ) {
        sb.append("110")
        n -= 1
        m -= 2
      }
      while (m > 0 && n > 0) {
        sb.append("10")
        m -= 1
        n -= 1
      }
      var pos = sb.indexOf('1')
      while (n > 0) {
        sb.insert(pos + 1, '0')
        pos = sb.indexOf('1', pos + 2)
        n -= 1
      }
      while (m > 0) {
        sb.append('1')
        m -= 1
      }
      out.println(sb.toString())
    }
    return 0
  }
}

import java.util.Scanner
import java.io.PrintWriter

/**
 * Created by hama_du on 2014/03/11.
 */
object ProblemC extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val zero,one = in.nextInt

  if (zero >= one+2) {
    out.println(-1)
  } else {
    val maxOne = (zero+1)*2
    if (one > maxOne) {
      out.println(-1)
    } else {
      if (zero >= one) {
        printZO(zero, one)
      } else {
        printOOZ(zero, one, one - (zero+1))
      }
      out.println()
    }
  }
  out.flush()

  def printOOZ(zero: Int, one: Int, dblOne: Int) {
    if (zero == 0) {
      if (dblOne == 1) {
        out.print("11")
      } else {
        out.print("1")
      }
    } else {
      if (dblOne >= 1) {
        out.print("110")
      } else {
        out.print("10")
      }
      printOOZ(zero-1, one-1, dblOne-1)
    }
  }

  def printZO(zero: Int, one: Int) {
    if (one == 0) {
      if (zero == 1) {
        out.print('0')
      }
    } else {
      out.print("01")
      printZO(zero-1, one-1)
    }
  }
}

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

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

object C401 {

  var result = true
  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)

  def solve: Int = {
    var n = nextInt
    var m = nextInt
    if (n > m + 1)
      out.println(-1)
    else if (n == m + 1) {
      for (i <- 0 until (n + m - 1) / 2) {
        out.print("01")
      }
      out.println("0")
    } else if (m > 2 * n + 2) {
      out.println(-1)
    } else {
      val sb = new StringBuilder()
      while (n >= 1 && m >= 2) {
        sb.append("110")
        n -= 1
        m -= 2
      }
      while (m > 0) {
        sb.append('1')
        m -= 1
      }
      out.println(sb.toString())
    }
    return 0
  }
}

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

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

object C401 {

  var result = true
  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)

  def solve: Int = {
    var n = nextInt
    var m = nextInt
    if (n > m + 1)
      out.println(-1)
    else if (n == m + 1) {
      for (i <- 0 until (n + m - 1) / 2) {
        out.print("01")
      }
      out.println("0")
    } else if (m > 2 * n + 2) {
      out.println(-1)
    } else {
      val sb = new StringBuilder()
      while (n >= 1 && m >= 2) {
        sb.append("110")
        n -= 1
        m -= 2
      }
      while (m > 0) {
        sb.append('1')
        m -= 1
      }
      var pos = sb.indexOf('1')
      while (n > 0) {
        sb.insert(pos + 1, '0')
        pos = sb.indexOf('1', pos + 2)
        n -= 1
      }
      out.println(sb.toString())
    }
    return 0
  }
}

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

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

object C401 {

  var result = true
  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)

  def solve: Int = {
    var n = nextInt
    var m = nextInt
    if (n > m + 1)
      out.println(-1)
    else if (n == m + 1) {
      for (i <- 0 until (n + m - 1) / 2) {
        out.print("01")
      }
      out.println("0")
    } else if (m > 2 * n + 2) {
      out.println(-1)
    } else {
      val sb = new StringBuilder()
      while (n != m) {
        sb.append("110")
        n -= 1
        m -= 2
      }
      while (m > 0 && n > 0) {
        sb.append("10")
        m -= 1
        n -= 1
      }
      var pos = sb.indexOf('1')
      while (n > 0) {
        sb.insert(pos + 1, '0')
        pos = sb.indexOf('1', pos + 2)
        n -= 1
      }
      out.println(sb.toString())
    }
    return 0
  }
}

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

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

object C401 {

  var result = true
  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)

  def solve: Int = {
    var n = nextInt
    var m = nextInt
    if (n > m + 1)
      out.println(-1)
    else if (n == m + 1) {
      for (i <- 0 until n + m - 1) {
        out.print("01")
      }
      out.println("0")
    } else if (m > 2 * n + 2) {
      out.println(-1)
    } else {
      val sb = new StringBuilder()
      while (n >= 1 && m >= 1) {
        sb.append("10")
        n -= 1
        m -= 1
      }
      var pos = sb.indexOf('1')
      while (m > 0 && pos != -1) {
        sb.insert(pos + 1, '1')
        pos = sb.indexOf('1', pos + 2)
        m -= 1
      }
      while (m > 0) {
        sb.append('1')
        m -= 1
      }
      out.println(sb.toString())
    }
    return 0
  }
}

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

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

object C401 {

  var result = true
  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)

  def solve: Int = {
    var n = nextInt
    var m = nextInt
    if (n > m + 1)
      out.println(-1)
    else if (n == m + 1) {
      for (i <- 0 until (n + m - 1) / 2) {
        out.print("01")
      }
      out.println("0")
    } else if (m > 2 * n + 2) {
      out.println(-1)
    } else {
      val sb = new StringBuilder()
      while (n >= 1 && m >= 2) {
        sb.append("110")
        n -= 1
        m -= 2
      }
      while (m > 0) {
        sb.append('1')
        m -= 1
      }
      while (n > 0) {
        sb.insert(0, '0')
        n -= 1
      }
      out.println(sb.toString())
    }
    return 0
  }
}


ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows of seats in the bus. Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.  Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.

If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output). If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line. If there are multiple solutions, you may print any of them.

NoteNote that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.O+|+XXO|XXOX|OOXX|OXOO|OOOO|XX

import java.util.Scanner

object Main extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt()
    val good = collection.immutable.HashMap("OO|XX" -> "++|XX", "OO|OX" -> "++|OX",
                                            "OO|XO" -> "++|XO", "OO|OO" -> "++|OO",
                                            "XX|OO" -> "XX|++", "XO|OO" -> "XO|++",
                                            "OX|OO"->"OX|++")

    val input = for (i <- 1 to n) yield scan.next()
    val yes = input.exists(good.contains(_))
    if (yes) {
        println("YES")
        var found = false
        input foreach { line =>
            if (!found && good.contains(line)) {
                found = true
                println(good.get(line).get)
            } else {
                println(line)
            }
        }
    } else {
        println("NO")
    }
}

import scala.io.StdIn._;

object Test extends App {
  val n = readInt();
  val ans = (for (i<-0 until n) yield readLine()).mkString("\n");
  if (ans.contains("OO")) {
    println("YES");
    println(ans.replaceFirst("OO", "++"));
  } else {
    println("NO\n");
  }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val (bus, ans) = (1 to n).map(_ => lines.next()).foldLeft(List.empty[String], false) {
    case ((xs, true), el) => (el :: xs, true)
    case ((xs, false), el) if el.contains("OO") => (el.replaceFirst("OO", "++") :: xs, true)
    case ((xs, false), el) => (el :: xs, false)
  }
  if (ans) {
    println("YES")
    println(bus.reverse.mkString("\n"))
  } else println("NO")
}

object A711 {
  @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) = readInts(1)
    val input = Array.fill(n)(scala.io.StdIn.readLine)
    if(input.exists(_.contains("OO"))) {
      println("YES")
      var break = false
      var i = 0
      while(!break) {
        if(input(i).contains("OO")) {
          input(i) = input(i).replaceFirst("OO", "++")
          break = true
        }
        i += 1
      }
      println(input.mkString("\n"))
    } else {
      println("NO")
    }
  }
}

object A extends App {

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

  val Array(n) = readInts(1)
  val rows = Array.fill(n){ readLine }

  val i = rows.indexWhere(_.contains("OO"))

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

  if (i == -1) println("NO")
  else {
    println("YES")
    rows(i) = rows(i).replaceFirst("OO", "++")
    println(rows.mkString("\n"))
  }

  Console.flush
}

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

object _711A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val bus = read[Seq[String]].mkString("\n")
    val ans = if (bus.contains("OO")) {
      "YES\n" + bus.replaceFirst("OO", "++")
    } else {
      "NO"
    }

    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 toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  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 writeAll(obj: Traversable[Any], separator: String = "\n"): 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 Solution {

  def main(args: Array[String]): Unit = {
    val n = readInt
    val bus = Array.fill(n)(readLine)
    val idx = bus.indexWhere(str => str.contains("OO"))
    if (idx == -1) {
      println("NO")
    } else {
      println("YES")
      bus.updated(idx, bus(idx).replaceFirst("OO", "++")).foreach(str => println(str))
    }
  }
}

import scala.io.StdIn._

object Solution {

  def main(args: Array[String]): Unit = {
    val bus = Array.fill(readInt)(readLine)
    val idx = bus.indexWhere(str => str.contains("OO"))
    if (idx == -1) {
      println("NO")
    } else {
      println("YES")
      bus.updated(idx, bus(idx).replaceFirst("OO", "++")).foreach(str => println(str))
    }
  }
}

object test {
  def main(args: Array[String]): Unit = {
    val num = Integer.parseInt(Console.readLine().trim)
    val out = Stream.continually(Console.readLine()).take(num).mkString("\n").replaceFirst("OO", "++")
    println(if (out.contains("++")) s"YES\n$out" else "NO")
  }

}

object test {
  def main(args: Array[String]): Unit = {
    val in = Console.in
    val num = Integer.parseInt(in.readLine().trim)
    val out = 1 to num map (i => in.readLine()) mkString "\n"  replaceFirst("OO", "++")
    if (out.contains("++"))
      println(s"YES\n$out")
    else println("NO")
  }

}

import java.util.Scanner

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

  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    sc.nextLine()
    val seats = new Array[String](n)
    for(i <- 0 until n)
      seats(i) = sc.nextLine()

    //
    var flag = false
    var i = 0
    while(!flag && i < n){
      val now = seats(i)
      if(now.substring(0, 2) == "OO"){
        flag = true
        seats(i) = "++" + now.substring(2)
      }
      else if(now.substring(3) == "OO"){
        flag = true
        seats(i) = now.substring(0, 3) + "++"
      }

      i += 1
    }

    if(flag){
      println("YES")
      for(s <- seats)
        println(s)
    }
    else
      println("NO")
  }
}

object main extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
 // override
  def solve(input: InputStream, output: PrintStream): Unit = {
    val sc = new Scanner(input)
    val nrows = sc.nextInt()
    val busIndx = (1 to nrows)
              .map(_ => sc.next()).zipWithIndex.toArray
    val optRow = busIndx.find{case (str,_) => str.startsWith("OO") || str.endsWith("OO")}
    if(optRow.isDefined){
      val (row,indxRow) = optRow.get
      busIndx(indxRow) = (updateRow(row),indxRow)

      output.println("YES")
      busIndx.foreach{case (str,_) => output.println(str)}
    }else{
      output.println("NO")
    }

  }

  def updateRow(str: String): String = {
    if(str.startsWith("OO")) "++"+str.substring(2)
    else str.substring(0,3)+ "++"
  }
  solve(System.in,System.out)
}

import java.util

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val max = 1000000007;
    val n = readInt()

    val  A:Array[Array[String]] = Array.fill(n)(StdIn.readLine().split('|'))

    var i = 0
    while(i != n && !A(i)(0).equals("OO") && !A(i)(1).equals("OO")) {
      i+=1
    }

    if(i!=n) {
      println("YES")
      if(A(i)(0).equals("OO"))
        A(i)(0) = "++"
      else
        A(i)(1) = "++"

      A.foreach(a=>println(a(0) + "|" + a(1)))
    } else {
      println("NO")
    }
  }

  def readInt(): Int = StdIn.readInt()

  def readInts(): Array[Int] = StdIn.readLine().split(" ").map(_.toInt)

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

}

import java.util.Scanner

object Main extends App {
    val scan = new Scanner(System.in)
    val n = scan.nextInt()
    val good = collection.immutable.HashMap("OO|XX" -> "++|XX", "OO|OX" -> "++|OX",
                                            "OO|XO" -> "++|XO", "OO|OO" -> "++|OO",
                                            "XX|OO" -> "XX|++", "XO|OO" -> "XO|++",
                                            "OX|OO"->"OX|++")

    val input = for (i <- 1 to n) yield scan.next()
    val yes = input.exists(good.contains(_))
    if (yes) {
        println("YES")
        var found = false
        input foreach { line =>
            if (!found && good.contains(line)) {
                found = true
                println(good.get(line).get)
            } else {
                println(line)
            }
        }
    } else {
        println("NO")
        input foreach println
    }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val (bus, ans) = (1 to n).map(_ => lines.next()).foldLeft(List.empty[String], false) {
    case ((xs, true), el) => (el :: xs, true)
    case ((xs, false), el) if el.contains("OO") => (el.replace("OO", "++") :: xs, true)
    case ((xs, false), el) => (el :: xs, false)
  }
  if (ans) println("YES") else println("NO")
  println(bus.reverse.mkString("\n"))
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val (bus, ans) = (1 to n).map(_ => lines.next()).foldLeft(List.empty[String], false) {
    case ((xs, true), el) => (el :: xs, true)
    case ((xs, false), el) if el.contains("OO") => (el.replace("OO", "++") :: xs, true)
    case ((xs, false), el) => (el :: xs, false)
  }
  if (ans) {
    println("YES")
    println(bus.reverse.mkString("\n"))
  } else println("NO")
}

object A711 {
  @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) = readInts(1)
    val input = Array.fill(n)(scala.io.StdIn.readLine)
    if(input.exists(_.contains("OO"))) {
      println("YES")
      var break = false
      var i = 0
      while(!break) {
        if(input(i).contains("OO")) {
          input(i) = input(i).replace("OO", "++")
          break = true
        }
        i += 1
      }
      println(input.mkString("\n"))
    } else {
      println("NO")
    }
  }
}

object test {
  def main(args: Array[String]): Unit = {
    val num = Integer.parseInt(Console.readLine().trim)
    val out = Stream.continually(Console.readLine()).take(num).mkString("\n").replaceFirst("00", "++")
    println(if (out.contains("++")) s"YES\n$out" else "NO")
  }

}

object test {
  def main(args: Array[String]): Unit = {
    val in = Console.in
    val num = Integer.parseInt(in.readLine().trim)
    val out = 1 to num map (i => in.readLine()) mkString "\n"  replaceFirst("00", "++")
    if (out.contains("++"))
      println(s"YES\n$out")
    else println("NO")
  }

}


Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this:  Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result:  He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.

NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

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

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

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

  def solve2(): Int = {
    val N = ni()
    val A = na(N).reverse
    val B = na(N)
    val cnt1 = A.count(_ == 1) + B.count(_ == 1)
    val cnt2 = 2 * N - cnt1
    val bal = cnt1 - cnt2
    val A2 = A.map(a => if (a == 1) 1 else -1)
    val B2 = B.map(a => if (a == 1) 1 else -1)
    val sumA = cumSum(A2).map(_.toInt)
    val sumB = cumSum(B2).map(_.toInt)
    debug(sumA)
    debug(sumB)
    debug(s"bal:$bal")
    val ref = mutable.Map[Int, Int]()
    REP(N + 1) { i =>
      val v = sumB(i)
      if (!ref.contains(v)) {
        ref(v) = i
      }
    }

    debug(ref.mkString(","))

    var ans = 2 * N
    REP(N + 1) { i =>
      val expectedB = bal - sumA(i)
//      debug(s"i:$i expectedB:$expectedB")
      if (ref.contains(expectedB)) {
        ans = min(ans, ref(expectedB) + i)
      }
    }
    ans
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      out.println(solve2())
    }
  }
}

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val t = stdin.next().toInt
  println(stdin
    .take(2 * t)
    .grouped(2)
    .map(_.last)
    .map(_
      .split(' ')
      .map(_.toInt)
      .map(x => if (x == 1) 1 else -1))
    .map(solve)
    .mkString("\n"))

  def solve(arr: Array[Int]) = {
    val n = arr.length / 2
//    val globalSum = arr.sum
    val leftSum = arr.take(n).sum
    val rightSum = arr.drop(n).sum
//    println(arr.mkString(" "))
//    println("leftSum " + leftSum)
//    println("rightSum " + rightSum)
//    println("globalSum " + globalSum)
    //1 1 1 -1 -1 1 ||| -1 1 -1 1 1 -1
    val map = arr.take(n).foldLeft(Map(0 -> n, leftSum -> 0), 0, n) {
      case ((map, sum, needToRemove), el) =>
        val nSum = sum + el
        val nNeedToRemove = needToRemove - 1
        val nMap = if (nSum != leftSum) map + (nSum -> nNeedToRemove) else map
        (nMap, nSum, nNeedToRemove)
    }._1
//    println(map)
    arr.drop(n).foldLeft(map.getOrElse(-rightSum, 2 * n), rightSum, 0) {
      case((res, sum, needToRemove), el) =>
//        println("el = " + el)
//        println(res)
        val nSum = sum - el
        val nNeedToRemove = needToRemove + 1
        val minRes = Math.min(res, map.get(-nSum).map(_ + nNeedToRemove).getOrElse(res))
        (minRes, nSum, nNeedToRemove)
    }._1
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val t = stdin.next().toInt
  println(stdin
    .take(2 * t)
    .grouped(2)
    .map(_.last)
    .map(_
      .split(' ')
      .map(_.toInt)
      .map(x => if (x == 1) 1 else -1))
    .map(solve)
    .mkString("\n"))

  def solve(arr: Array[Int]) = {
    val n = arr.length / 2
//    val globalSum = arr.sum
    val leftSum = arr.take(n).sum
    val rightSum = arr.drop(n).sum
//    println(arr.mkString(" "))
//    println("leftSum " + leftSum)
//    println("rightSum " + rightSum)
//    println("globalSum " + globalSum)
    //1 1 1 -1 -1 1 ||| -1 1 -1 1 1 -1
    val map = arr.take(n).foldLeft(Map(leftSum -> 0), 0, n) {
      case ((map, sum, needToRemove), el) =>
        val nSum = sum + el
        val nNeedToRemove = needToRemove - 1
        val nMap = if (nSum != leftSum) map + (nSum -> nNeedToRemove) else map
        (nMap, nSum, nNeedToRemove)
    }._1
    arr.drop(n).foldLeft(map.getOrElse(-rightSum, 2 * n), 0, 0) {
      case((res, sum, needToRemove), el) =>
//        println("el = " + el)
//        println(res)
        val nSum = sum + el
        val nNeedToRemove = needToRemove + 1
        val minRes = Math.min(res, map.get(-rightSum + nSum).map(_ + nNeedToRemove).getOrElse(res))
        (minRes, nSum, nNeedToRemove)
    }._1
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val t = stdin.next().toInt
  println(stdin
    .take(2 * t)
    .grouped(2)
    .map(_.last)
    .map(_
      .split(' ')
      .map(_.toInt)
      .map(x => if (x == 1) 1 else -1))
    .map(solve)
    .mkString("\n"))

  def solve(arr: Array[Int]) = {
    val n = arr.length / 2
//    val globalSum = arr.sum
    val leftSum = arr.take(n).sum
    val rightSum = arr.drop(n).sum
//    println(arr.mkString(" "))
//    println("leftSum " + leftSum)
//    println("rightSum " + rightSum)
//    println("globalSum " + globalSum)
    //1 1 1 -1 -1 1 ||| -1 1 -1 1 1 -1
    val map = arr.take(n).foldLeft(Map(leftSum -> 0, 0 -> n), 0, n) {
      case ((map, sum, needToRemove), el) =>
        val nSum = sum + el
        val nNeedToRemove = needToRemove - 1
        val nMap = if (nSum != leftSum) map + (nSum -> nNeedToRemove) else map
        (nMap, nSum, nNeedToRemove)
    }._1
//    println(map)
    arr.drop(n).foldLeft(map.getOrElse(-rightSum, 2 * n), rightSum, 0) {
      case((res, sum, needToRemove), el) =>
//        println("el = " + el)
//        println(res)
        val nSum = sum - el
        val nNeedToRemove = needToRemove + 1
        val minRes = Math.min(res, map.get(-nSum).map(_ + nNeedToRemove).getOrElse(res))
        (minRes, nSum, nNeedToRemove)
    }._1
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val t = stdin.next().toInt
  println(stdin
    .take(2 * t)
    .grouped(2)
    .map(_.last)
    .map(_
      .split(' ')
      .map(_.toInt)
      .map(x => if (x == 1) 1 else -1))
    .map(solve)
    .mkString("\n"))

  def solve(arr: Array[Int]) = {
    val n = arr.length / 2
//    val globalSum = arr.sum
    val leftSum = arr.take(n).sum
    val rightSum = arr.drop(n).sum
//    println(arr.mkString(" "))
//    println("leftSum " + leftSum)
//    println("rightSum " + rightSum)
//    println("globalSum " + globalSum)
    //1 1 1 -1 -1 1 ||| -1 1 -1 1 1 -1
    val map = arr.take(n).foldLeft(Map(leftSum -> 0), 0, n) {
      case ((map, sum, needToRemove), el) =>
        val nSum = sum + el
        val nNeedToRemove = needToRemove - 1
        val nMap = if (nSum != leftSum) map + (nSum -> nNeedToRemove) else map
        (nMap, nSum, nNeedToRemove)
    }._1
    arr.drop(n).foldLeft(map.getOrElse(-rightSum, 2 * n), rightSum, 0) {
      case((res, sum, needToRemove), el) =>
//        println("el = " + el)
//        println(res)
        val nSum = sum - el
        val nNeedToRemove = needToRemove + 1
        val minRes = Math.min(res, map.get(-nSum).map(_ + nNeedToRemove).getOrElse(res))
        (minRes, nSum, nNeedToRemove)
    }._1
  }
}

//1
//6
//1 1 1 2 2 1 2 1 2 1 1 2