object Main
{
	def min (a : Int, b : Int) : Int =
		if (a < b) return a
		else return b
	def main (args : Array[String]) =
	{
		var parni = scala.collection.mutable.Map[Int,Int]()
		var neparni = scala.collection.mutable.Map[Int,Int]()

		val n = readLine.toInt
		val arr = readLine.split(' ').map(_.toInt)

		var dp = new Array[Int](n+2)
		dp(0) = 0
		for (i <- 1 to n)
			dp(i) = dp(i-1) ^ arr(i-1)
		var rez : BigInt = 0

		parni.update(0,1)

		for (i <- 1 to n)
		{
			//println("za i = " + i)
			var a = dp(i)
			//println("a = " + a)
			var b = 0

			if (i%2 == 1 && neparni.contains(a))
				b = neparni(a)
			else if (i%2 == 0 && parni.contains(a))
				b = parni(a)

			//println("b = " + b)

			rez += b
			//println("rez = " + rez)

			if (i%2 == 0)
				parni.update(a,b+1)
			else
				neparni.update(a,b+1)
		}
		println(rez)
	}
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = nal(N)
    val cum = Array.ofDim[Long](N + 1)
    REP(N) { i =>
      cum(i + 1) = cum(i) ^ A(i)
    }

//    debug(cum)

    class Counter {
      var even: Long = 0
      var odd: Long = 0

      override def toString: String = s"($even, $odd)"
    }
    val ix = mutable.Map[Long, Counter]()
    REP(N + 1) { i =>
      if (!ix.contains(cum(i))) ix(cum(i)) = new Counter
      if (i % 2 == 0) ix(cum(i)).even += 1
      else ix(cum(i)).odd += 1
    }

//    debug(ix.mkString)

    var ans = 0L
    ix.foreach { case (_, cnt) =>
      ans += cnt.even * (cnt.even - 1) / 2
      ans += cnt.odd * (cnt.odd - 1) / 2
    }

    out.println(ans)
  }

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

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

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

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

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

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

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

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

object Main
{
	def min (a : Int, b : Int) : Int =
		if (a < b) return a
		else return b
	def main (args : Array[String]) =
	{
		var parni = scala.collection.mutable.Map[Int,Int]()
		var neparni = scala.collection.mutable.Map[Int,Int]()

		val n = readLine.toInt
		val arr = readLine.split(' ').map(_.toInt)

		var dp = new Array[Int](n+2)
		dp(0) = 0
		for (i <- 1 to n)
			dp(i) = dp(i-1) ^ arr(i-1)
		var rez = 0

		parni.update(0,1)

		for (i <- 1 to n)
		{
			//println("za i = " + i)
			var a = dp(i)
			//println("a = " + a)
			var b = 0

			if (i%2 == 1 && neparni.contains(a))
				b = neparni(a)
			else if (i%2 == 0 && parni.contains(a))
				b = parni(a)

			//println("b = " + b)

			rez += b
			//println("rez = " + rez)

			if (i%2 == 0)
				parni.update(a,b+1)
			else
				neparni.update(a,b+1)
		}
		println(rez)
	}
}


import scala.io.StdIn

object YetAnotherArrayPartition {
  def main(args: Array[String]): Unit = {
    val content = StdIn.readLine()
    val line1Arg = content.split(" ")
    val nums = line1Arg(0).toInt
    val minSize = line1Arg(1).toInt
    val partitions = line1Arg(2).toInt
    val line2 = StdIn.readLine()
    val line2Arg = line2.split(" ")
    val arrayBuffer = scala.collection.mutable.ArrayBuffer[Int]()
    for (i <- 0 until nums) {
      arrayBuffer.append(line2Arg(i).toInt)
    }
    val validNum = minSize * partitions
    val sorted = arrayBuffer.sorted.reverse
    val minValid = sorted(validNum - 1)
    var idx = validNum - 1
    var minValidNumCount = 0
    while (idx >= 0 && minValid == sorted(idx)) {
      minValidNumCount += 1
      idx -= 1
    }
    val splitArray = scala.collection.mutable.ListBuffer[Int]()
    var splitIdx = 0
    var remainValidCount = minValidNumCount
    var curPartitionValidNums = 0
    var i = 0
    var break = false
    var curPartitionSum = 0L
    var totalSum = 0L
    while (i < nums && !break) {
      if (arrayBuffer(i) > minValid) {
        curPartitionValidNums += 1
        curPartitionSum += arrayBuffer(i)
        if (curPartitionValidNums == minSize) {
          totalSum += curPartitionSum
          curPartitionSum = 0
          curPartitionValidNums = 0
          splitIdx += 1
          if (splitIdx != partitions) {
            splitArray.append(i + 1)
          }
        }
      } else if (arrayBuffer(i) == minValid && remainValidCount > 0) {
        remainValidCount -= 1
        curPartitionValidNums += 1
        curPartitionSum += arrayBuffer(i)
        if (curPartitionValidNums == minSize) {
          totalSum += curPartitionSum
          curPartitionSum = 0
          curPartitionValidNums = 0
          splitIdx += 1
          if (splitIdx != partitions) {
            splitArray.append(i + 1)
          }
        }
      } else {

      }

      if (splitIdx == partitions) {
        break = true
      }
      i += 1
    }
    println(totalSum)
    println(splitArray.mkString(" "))
  }
}

import scala.io.StdIn.readLine

object B1114ArraySplit extends App {
  val n::m::k::_ = readLine().split(" ").map(_.toInt).toList
  val as = readLine().split(" ").map(BigInt(_)).toList

  val cuts = as.zipWithIndex.sortBy(_._1).takeRight(m * k).map(_._2).sorted.zipWithIndex.filter(x => x._2 % m == 0).map(_._1).tail

  println(as.sorted.takeRight(m * k).sum)
  println(cuts.mkString(" "))
}

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

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

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N, M, K = ni()
    val A = na(N)
    val ix = Array.ofDim[Integer](N)
    REP(N) { i =>
      ix(i) = i
    }

    // Aの降順で並べる
    java.util.Arrays.sort(ix, new Comparator[Integer] {
      override def compare(o1: Integer, o2: Integer): Int = Integer.compare(A(o2), A(o1))
    })

    // ixの昇順でソート
    val B = ix.take(M * K)
    java.util.Arrays.sort(B, new Comparator[Integer] {
      override def compare(o1: Integer, o2: Integer): Int = o1.compareTo(o2)
    })

    var S = 0L
    REP(B.length) { i =>
      S += A(B(i))
    }

    out.println(S)
//    debug(B.mkString(" "))

    val ans = ArrayBuffer[Int]()
    REP(K - 1, 1) { i =>
      ans += B(i * M - 1) + 1
    }
    out.println(ans.mkString(" "))
  }

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

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

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

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

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

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

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

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

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

object Codeforces114B {

  def getSubArrayPartitions(n: Int, m: Int, k: Int, a: Seq[Int]): (Long, Seq[Int]) = {
    val largerNumbers = a.sorted.reverse.take(m * k)
    val largeNumberFrequencyMap: mutable.Map[Int, Int] = toFrequencyMap(largerNumbers)
    val partition = new Array[Int](k - 1)
    var inputIndex = 0
    for (outputIndex <- partition.indices) {
      var subArrayIndex = 0
      while (subArrayIndex < m) {
        val element = a(inputIndex)
        if (largeNumberFrequencyMap.getOrElse(element, 0) > 0) {
          largeNumberFrequencyMap(element) -= 1
          subArrayIndex += 1
        }
        inputIndex += 1
      }
      partition(outputIndex) = inputIndex
    }
    (largerNumbers.map(_.toLong).sum, partition)
  }

  private def toFrequencyMap(numbers: Seq[Int]): mutable.Map[Int, Int] = {
    val frequencyMap = new mutable.HashMap[Int, Int]()
    for (number <- numbers) {
      frequencyMap(number) = frequencyMap.getOrElse(number, 0) + 1
    }
    frequencyMap
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)

    val result = getSubArrayPartitions(n, m, k, a)
    val sum = result._1
    val partition = result._2
    println(sum)
    println(partition.mkString(" "))
  }
}

import scala.io.StdIn.readLine

object B1114ArraySplit extends App {
  val n::m::k::_ = readLine().split(" ").map(_.toInt).toList
  val as = readLine().split(" ").map(_.toInt).toList

  println(as.sorted.takeRight(m * k).sum)
  println((1 until k).map(x => x * m).mkString(" "))
}

import scala.io.StdIn.readLine

object B1114ArraySplit extends App {
  val n::m::k::_ = readLine().split(" ").map(_.toInt).toList
  val as = readLine().split(" ").map(_.toInt).toList

  val cuts = as.zipWithIndex.sortBy(_._1).takeRight(m * k).map(_._2).sorted.zipWithIndex.filter(x => x._2 % m == 0).map(_._1).tail

  println(as.sorted.takeRight(m * k).sum)
  println(cuts.mkString(" "))
}

import scala.io.StdIn

object YetAnotherArrayPartition {
  def main(args: Array[String]): Unit = {
    val content = StdIn.readLine()
    val line1Arg = content.split(" ")
    val nums = line1Arg(0).toInt
    val minSize = line1Arg(1).toInt
    val partitions = line1Arg(2).toInt
    val line2 = StdIn.readLine()
    val line2Arg = line2.split(" ")
    val arrayBuffer = scala.collection.mutable.ArrayBuffer[Int]()
    for (i <- 0 until nums) {
      arrayBuffer.append(line2Arg(i).toInt)
    }
    val validNum = minSize * partitions
    val sorted = arrayBuffer.sorted.reverse
    val minValid = sorted(validNum - 1)
    var idx = validNum - 1
    var minValidNumCount = 0
    while (minValid == sorted(idx)) {
      minValidNumCount += 1
      idx -= 1
    }
    val splitArray = scala.collection.mutable.ListBuffer[Int]()
    var splitIdx = 0
    var remainValidCount = minValidNumCount
    var curPartitionValidNums = 0
    var i = 0
    var break = false
    var curPartitionSum = 0
    var totalSum = 0
    while (i < nums && !break) {
      if (arrayBuffer(i) > minValid) {
        curPartitionValidNums += 1
        curPartitionSum += arrayBuffer(i)
        if (curPartitionValidNums == minSize) {
          totalSum += curPartitionSum
          curPartitionSum = 0
          curPartitionValidNums = 0
          splitIdx += 1
          if (splitIdx != partitions) {
            splitArray.append(i + 1)
          }
        }
      } else if (arrayBuffer(i) == minValid && remainValidCount > 0) {
        remainValidCount -= 1
        curPartitionValidNums += 1
        curPartitionSum += arrayBuffer(i)
        if (curPartitionValidNums == minSize) {
          totalSum += curPartitionSum
          curPartitionSum = 0
          curPartitionValidNums = 0
          splitIdx += 1
          if (splitIdx != partitions) {
            splitArray.append(i + 1)
          }
        }
      } else {

      }

      if (splitIdx == partitions) {
        break = true
      }
      i += 1
    }
    println(totalSum)
    println(splitArray.mkString(" "))
  }
}

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

object Codeforces114B {

  def getSubArrayPartitions(n: Int, m: Int, k: Int, a: Seq[Int]): (Int, Seq[Int]) = {
    val largerNumbers = a.sorted.reverse.take(m * k)
    val largeNumberFrequencyMap: mutable.Map[Int, Int] = toFrequencyMap(largerNumbers)
    val partition = new Array[Int](k - 1)
    var inputIndex = 0
    for (outputIndex <- partition.indices) {
      var subArrayIndex = 0
      while (subArrayIndex < m) {
        val element = a(inputIndex)
        if (largeNumberFrequencyMap.getOrElse(element, 0) > 0) {
          largeNumberFrequencyMap(element) -= 1
          subArrayIndex += 1
        }
        inputIndex += 1
      }
      partition(outputIndex) = inputIndex
    }
    (largerNumbers.sum, partition)
  }

  private def toFrequencyMap(numbers: Seq[Int]): mutable.Map[Int, Int] = {
    val frequencyMap = new mutable.HashMap[Int, Int]()
    for (number <- numbers) {
      frequencyMap(number) = frequencyMap.getOrElse(number, 0) + 1
    }
    frequencyMap
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)

    val result = getSubArrayPartitions(n, m, k, a)
    val sum = result._1
    val partition = result._2
    println(sum)
    println(partition.mkString(" "))
  }
}


import java.util

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A217 extends App {

  def dfs(g: mutable.Map[Int, util.ArrayList[Int]], start: Int, visited: Array[Boolean]): Unit = {
    visited(start) = true
    if (g.contains(start)) {
      val neighbors: util.ArrayList[Int] = g(start)
      for (i <- 0 until neighbors.size()) {
        val neighbor: Int = neighbors.get(i)
        if (!visited(neighbor)) {
          dfs(g, neighbor, visited)
        }
      }
    }
  }

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val coords: Array[(Int, Int)] = Array.ofDim(n)
    for (i <- 0 until n) {
      val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      coords(i) = (x, y)
    }
    val g: mutable.Map[Int, util.ArrayList[Int]] = mutable.Map.empty[Int, util.ArrayList[Int]]
    for (i <- 0 until n) {
      for (j <- i+1 until n) {
        if (coords(i)._1 == coords(j)._1 || coords(i)._2 == coords(j)._2) {
          if (!g.contains(i)) {
            g += (i -> new util.ArrayList[Int]())
          }
          g(i).add(j)
          if (!g.contains(j)) {
            g += (j -> new util.ArrayList[Int]())
          }
          g(j).add(i)
        }
      }
    }
    val visited: Array[Boolean] = Array.ofDim(n)
    var c = 0
    for (i <- 0 until n) {
      if (!visited(i)) {
        dfs(g, i, visited)
        c += 1
      }
    }
    println(c-1)
  }

  solve()

}

object IceSkating {
  case class Edge(u:Int,v:Int) {
    def ==(that:Edge):Boolean={
      return (this.u==that.u)||(this.v==that.v)
    }
  }
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var n=in.readInt()
    val edges=Array.fill[Edge](n)(null)
    for(i<- 0 until n){
      val arr=in.readLine().split(" ").map(_.toInt)
      edges(i)=Edge(arr(0),arr(1))
    }

    //The intuition is to find connected component using dfs
    //and we will consider two component is connected is two points are fall under same x or y co-ordinate
    val visited=Array.fill[Boolean](n)(false)
    var cou=0
    for(i<- 0 until edges.length ){
      if(!visited(i)){
        cou+=1
        dfs(edges,visited,i)
      }
    }
    println(cou-1)
  }
  def dfs(edges:Array[Edge],vis:Array[Boolean],n:Int):Unit={
    vis(n)=true
    for(i<- 0 until edges.length if(!vis(i) && edges(i)==edges(n))){
      dfs(edges,vis,i)
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var cache = Set.empty[(Set[Int], Set[Int])]
  Range(0, n).map{_ =>
    in.next().split(" ").map(_.toInt)
  }.foreach {
    case Array(a, b) =>
      val first = cache.find(_._1.contains(a))
      val second = cache.find(_._2.contains(b))
      if (first.isEmpty && second.isEmpty)
        cache += ((Set(a), Set(b)))
      else if (first.isDefined && second.isDefined) {
        cache -= first.get
        cache -= second.get
        cache += ((first.get._1 ++ second.get._1, first.get._2 ++ second.get._2))
      } else if (first.isDefined) {
        cache -= first.get
        cache += ((first.get._1 + a, first.get._2 + b))
      } else {
        cache -= second.get
        cache += ((second.get._1 + a, second.get._2 + b))
      }
  }
  println(cache.size - 1)
}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A217 extends App {

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val xs: mutable.Set[Int] = mutable.Set.empty[Int]
    val ys: mutable.Set[Int] = mutable.Set.empty[Int]
    for (i <- 0 until n) {
      val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      xs += x
      ys += y
    }
    println(Math.min(xs.size, ys.size) - 1)
  }

  solve()

}


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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)

    // [l, r]
    class Seg {
      var l: Int = -1
      var r: Int = -1
    }

    object Seg {
      def apply(l: Int, r: Int) = {
        val s = new Seg
        s.l = l
        s.r = r
        s
      }
    }

    // Aの初期セグメント
    val S = mutable.Map[Int, Seg]()
    REP(N) { i =>
      if (!S.contains(A(i))) S(A(i)) = Seg(i, i)
      else {
        val s = S(A(i))
        if (i < s.l) s.l = i
        else if (i > s.r) s.r = i
      }
    }

    val uf = new UnionFind(N)

    // unionfindのsetごとのセグメント
    val dynamicS = mutable.Map[Int, Seg]()
    REP(N) { i =>
      dynamicS(uf.find(i)) = Seg(i, i)
    }

    def uniteAll(ll: Int, r: Int): Unit = {
      var l = ll
      while(r > l) {
        uf.unite(l, l + 1)
        l += 1
      }
    }

    S.values.foreach { s =>
      // まだ同じセグメントになっていないなら２つのセグメントの間を全部融合する
      if (uf.find(s.l) != uf.find(s.r)) {
        val s1 = dynamicS(uf.find(s.l))
        val s2 = dynamicS(uf.find(s.r))
        // この２つのセグメントは必ず共通部分がない
        if (s1.l < s2.l) {
          uniteAll(s1.r, s2.l)
        } else {
          uniteAll(s2.r, s1.l)
        }

        dynamicS(uf.find(s.l)) = Seg(min(s1.l, s2.l), max(s1.r, s2.r))
      }
    }

    var ans = 1L
    val frees = countDisjointSets(uf) - 1 // b0が固定なので-1
    REP(frees) { _ =>
      ans = ans * 2 % MOD
    }

    out.println(ans)
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

  def countDisjointSets(uf: UnionFind): Int = {
    var cnt = 0
    REP(uf.n) { i =>
      if (uf.find(i) == i) cnt += 1
    }
    cnt
  }

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

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

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

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

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

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

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

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

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

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

object Main {
    import java.util.Scanner
    import java.io.PrintWriter
    import scala.collection.mutable.Map

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

    def main(args: Array[String]) {
        val MOD = 998244353
        def pwr2(e: Long): Long = {
            if (e == 0) 1
            else {
                val t: Long = pwr2(e / 2)
                if (e % 2 == 0) t * t % MOD
                else t * t * 2 % MOD
            }
        }

        val n = in.nextInt
        val a = (for (i <- 0 until n) yield in.nextInt).toArray
        val last = Map[Int, Int]()
        for (i <- 0 until n)
            last(a(i)) = i
        var r = -1
        var cnt = 0
        for (i <- 0 until n) {
            cnt = if (i > r) cnt + 1 else cnt
            r = if (last(a(i)) > r) last(a(i)) else r
        }
        println(pwr2(cnt - 1))
    }
}


object CF297B extends App{
  import scala.io.StdIn

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val sortedArray = StdIn
    .readLine()
    .split("\\s+")
    .map(x => x.toInt-1)
    .groupBy(x => x)
    .filter(valAndArray => valAndArray._2.length % 2 == 1)
    .keys
    .toArray
    .sorted

  for((valueFrom,index) <- sortedArray.view.zipWithIndex){
    if(index % 2 == 0){

      val valueUntil = if(sortedArray.length-1 == index)  inputLength/2 else sortedArray(index + 1)

      for(indexToChange <- valueFrom until valueUntil){
        val tmpValue = input(indexToChange)

        val oppositeIndexToChange = inputLength - indexToChange - 1

        input(indexToChange) = input(oppositeIndexToChange)

        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}

import scala.collection.mutable

object CF297B extends App{
  import scala.io.StdIn
  import scala.collection.mutable

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val inputArray = StdIn.readLine().split("\\s+").map(x => x.toInt-1).sorted.toList :+ inputLength / 2

//  val hashMap = new mutable.HashMap[Int, Int]()
//
//  inputArray.foreach(x => {
//    val value = hashMap.get(x)
//    var cnt = 1
//    if(value.isEmpty){
//      hashMap.put(x, 1)
//    } else {
//      hashMap.put(x, value.get + 1)
//    }
//  })
//
//  val sorted = hashMap.filter(keyValue => keyValue._2 % 2 == 1).keys.toList.sorted :+ inputLength / 2

  val sorted = mutable.MutableList[Int]()
  var prev = inputArray.head
  var cnt = 0
  inputArray.foreach(value => {
    if (prev != value){
      if(cnt % 2 == 1){
        sorted += prev
      }
      cnt = 1
      prev = value
    } else {
      cnt = cnt + 1
    }
  })
  if(cnt % 2 == 1)sorted += prev

  val arr = sorted.toArray

  for((value1,index) <- arr.view.zipWithIndex){
    if(index % 2 == 0 && index < arr.length-1){
      for(indexToChange <- value1 until arr(index+1)){
        val tmpValue = input(indexToChange)
        val oppositeIndexToChange = inputLength - indexToChange - 1
        input(indexToChange) = input(oppositeIndexToChange)
        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}

object CF297B extends App{
  import scala.io.StdIn
  import scala.collection.mutable

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val inputArray = StdIn.readLine().split("\\s+").map(x => x.toInt-1)

  val hashMap = new mutable.HashMap[Int, Int]()
  hashMap.put(inputLength / 2, 1)

  inputArray.foreach(x => {
    val value = hashMap.get(x)
    var cnt = 1
    if(value.isEmpty){
      hashMap.put(x, 1)
    } else {
      hashMap.put(x, value.get + 1)
    }
  })

  val arr = hashMap.filter(keyValue => keyValue._2 % 2 == 1).keys.toArray.sorted

  for((value1,index) <- arr.view.zipWithIndex){
    if(index % 2 == 0 && index < arr.length-1){
      for(indexToChange <- value1 until arr(index+1)){
        val tmpValue = input(indexToChange)
        val oppositeIndexToChange = inputLength - indexToChange - 1
        input(indexToChange) = input(oppositeIndexToChange)
        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}

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

import scala.StringBuilder
import scala.collection.mutable

object B {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def solve: Int = {
    val s = next.toCharArray
    val m = nextInt
    val length: Int = s.length
    val cnt = new Array[Int](length)
    val bitSet = new util.BitSet()
    val bits = new Array[Boolean](length)
    for (i <- 0 until length) {
      bits(i) = true
    }
    for (i <- 0 until m) {
      val x = nextInt - 1
      bits(x) = !bits(x)
      bits(length - x - 1) = !bits(length - x - 1)
    }
    var curr = 0
    val sb = new StringBuilder()
    for (i <- 0 until length / 2) {
      if (!bits(i)) {
        curr += 1
      }
      if (curr % 2 == 0) {
        out.print(s(i))
        sb.append(s(length - i - 1))
      } else {
        out.print(s(length - i - 1))
        sb.append((s(i)))
      }
    }
    if (length % 2 == 1) {
      out.print(s(length / 2))
    }
    out.println(sb.reverse.toString())
    return 0
  }
}

import java.lang.Math.pow

import scala.io.StdIn

/**
 * Created by pol on 29/03/15.
 */
object CR297_B extends App {
  var input = StdIn.readLine().toCharArray
  var m = StdIn.readInt()
  var ai = new Array[Int](pow(10d, 5d).toInt);
  for (i <- StdIn.readLine().trim().split(" ")) {
    ai(i.toInt-1) += 1
  }

  for (i <- 0 until input.length / 2) {
    if (i != 0) {
      ai(i) += ai(i - 1)
    }
    if (ai(i) % 2 == 1) {
      val left: Char = input(i)
      val right: Char = input(input.length - i - 1)
      input(i) = right
      input(input.length - i - 1) = left
    }
  }

  println(String.copyValueOf(input))
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val S=nextString.toCharArray
    val n=nextInt
    val a=Array.fill(n)(0)
    for(i<-0 until n){a(i)=nextInt-1}
    scala.util.Sorting.quickSort(a)
    var p=0
    var count=0
    for(i<-0 until S.length/2){

      while(p<n && a(p)==i){
        p+=1
        count+=1
      }
      if(count%2==1){
        val tmp=S(i)
        S(i)=S(S.length-i-1)
        S(S.length-i-1)=tmp
      }
    }
    for(i<-0 until S.length){out.print(S(i))}

    //code ends here
    out.flush
    out.close
  }
}

object CodeForces extends App {

  def solve = {
    val str = readLine
    val revStr = str.reverse
    val strLen = str.length
    val num = readLine toInt
    val opArr = readLine().split(' ').map(c => c.toInt)

    var revStatArr = Array.fill(strLen / 2)(0)
    for (op <- opArr if 2 * op <= strLen) {
      revStatArr(op - 1) += 1
    }

    var currRev = 0
    var sbF = new StringBuilder(strLen / 2)
    var sbB = new StringBuilder(strLen / 2)
    def isEven(n: Int) = n % 2 == 0

    for (i <- 0 until strLen / 2) {
      currRev += revStatArr(i)

      sbF append (if (isEven(currRev)) str(i) else revStr(i))
      sbB append (if (!isEven(currRev)) str(i) else revStr(i))
    }

    val resStr = sbF append (if (isEven(strLen)) "" else str(strLen / 2)) append sbB.reverse
    println(resStr)
  }

  solve
}

object CodeForces extends App {

  def solve = {
    val str = readLine
    val strLen = str.length
    val num = readLine toInt
    val opArr = readLine().split(' ').map(c => c.toInt)
    var revStatArr = Array.fill(strLen / 2)(0)

    for (op <- opArr if 2 * op <= strLen) {
      revStatArr(op - 1) += 1
    }

    var currRev = 0
    var sb = new StringBuilder(strLen)
    for (i <- 0 until strLen) sb += str(strLen / 2)
    def isEven(n: Int) = n % 2 == 0
    def oospar(i: Int) = strLen - i - 1

    for (i <- 0 until strLen / 2) {
      currRev += revStatArr(i)

      sb(i) = if (isEven(currRev)) str(i) else str(oospar(i))
      sb(oospar(i)) = if (!isEven(currRev)) str(i) else str(oospar(i))
    }

    val resStr = sb.toString()
    println(resStr)
  }

  solve
}

object CodeForces extends App {
    val str = readLine
    val revStr = str.reverse
    val strLen = str.length
    val num = readLine toInt
    val opArr = readLine().split(' ').map(c => c.toInt)

    val revStatArr = Array.fill(strLen / 2)(0)
    for (op <- opArr if 2 * op <= strLen) {
      revStatArr(op - 1) += 1
    }

    var currRev = 0
    val sbF = new StringBuilder(strLen / 2)
    val sbB = new StringBuilder(strLen / 2)

    def isEven(n: Int) = n % 2 == 0

    for (i <- 0 until strLen / 2) {
      currRev += revStatArr(i)
      sbF append (if (isEven(currRev)) str(i) else revStr(i))
      sbB append (if (!isEven(currRev)) str(i) else revStr(i))
    }

    println(sbF append (if (isEven(strLen)) "" else str(strLen / 2)) append sbB.reverse)
}

object CF297B extends App{
  import scala.io.StdIn

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val sortedArray = StdIn
    .readLine()
    .split("\\s+")
    .map(x => x.toInt-1)
    .groupBy(x => x)
    .filter(valAndArray => valAndArray._2.length % 2 == 1)
    .keys
    .toArray
    .sorted

  println("sortedArray" + sortedArray.map(x => x + 1).toList)

  for((valueFrom,index) <- sortedArray.view.zipWithIndex){
    if(index % 2 == 0){

      val valueUntil = if(sortedArray.length-1 == index)  inputLength/2 else sortedArray(index + 1)

      for(indexToChange <- valueFrom until valueUntil){
        val tmpValue = input(indexToChange)

        val oppositeIndexToChange = inputLength - indexToChange - 1

        input(indexToChange) = input(oppositeIndexToChange)

        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}

object CF297B extends App{
  import scala.io.StdIn

  val input = StdIn.readLine().toCharArray
  val inputLength = input.length
  val n: Int = StdIn.readInt()
  val sortedArray = StdIn
    .readLine()
    .split("\\s+")
    .map(x => x.toInt-1)
    .groupBy(x => x)
    .filter(valAndArray => valAndArray._2.length % 2 == 1)
    .keys
    .toArray
    .sorted

  for((valueFrom,index) <- sortedArray.view.zipWithIndex){
    if(index % 2 == 0){

      val valueUntil = if(sortedArray.length-1 == index)  inputLength/2 else index + 1

      for(indexToChange <- valueFrom until valueUntil){
        val tmpValue = input(indexToChange)

        val oppositeIndexToChange = inputLength - indexToChange - 1

        input(indexToChange) = input(oppositeIndexToChange)

        input(oppositeIndexToChange) = tmpValue
      }
    }
  }

  print (new String(input))

}


import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object ProbA {

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

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

   /*def primeFactorsWithout23(a: Int) : Map[Int,Int] = {
     def go(a: Int, factors : Map[Int,Int],p: Int) : Map[Int,Int] = {
       //println(s"testing $a : factors" + factors)
       if (a == 1) factors
       else if (a%p == 0)
               go(a/p, factors + (p -> (factors.getOrElse(p, 0) + 1))  ,p)
            else go(a,factors,p+2)
     }
     var x = a
     while (x%2 == 0) x = x/2
     while (x%3 == 0) x = x/3
     go(x,Map(),5)
   }*/

   def remove2(a: Int) : Int = {
     if (a%2 != 0) a else remove2(a/2)
   }
    def remove3(a: Int) : Int = {
     if (a%3 != 0) a else remove3(a/3)
   }

   def main(args: Array[String]) {
     val n = readInt
     val bids = readInts
    // val primeFactors = primeFactorsWithout23(bids(0))
     val reduced = remove2(remove3(bids(0)))
     if (bids.forall{ a => remove2(remove3(a)) == reduced})
       println("YES")
     else
       println("NO")

   }

}

//package round318.c

import java.util.Scanner

object Main extends App {

  def possible(a: Long, b: Long): Option[Long] = {

    import Math._
    var aa = a
    var k1 = 0
    var m1 = 0
    while(aa % 2 == 0) { aa /= 2; k1 += 1 }
    while(aa % 3 == 0) { aa /= 3; m1 += 1 }

    var bb = b
    var k2 = 0
    var m2 = 0
    while(bb % 2 == 0) { bb /= 2; k2 += 1 }
    while(bb % 3 == 0) { bb /= 3; m2 += 1 }

    if(aa != bb) None
    else Some((pow(2, max(k1,k2)) * pow(3, max(m1,m2))).toLong * aa)
  }

  val sc = new Scanner(System.in)

  val n = sc.nextInt
  var ok = true

  var bid = sc.nextLong

  (1 until n) foreach { _ =>
    val bid2 = sc.nextLong
    possible(bid, bid2) match {
      case None =>
        ok = false
      case Some(bid3) =>
        bid = bid3
    }
  }

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

}

object Codeforces extends App {
  val in = new java.util.Scanner(System.in)
  var n = in.nextInt()
  var a = Array.ofDim[Int](n);
  for (i <- 0 until n) {
    a(i) = in.nextInt()
    while (a(i) % 2 == 0) a(i) /= 2
    while (a(i) % 3 == 0) a(i) /= 3
  }
  var ok = true
  for (i <- 1 until n)
    if (a(i) != a(0))
      ok = false
  println(if (ok) "Yes" else "No")
}

object Solution extends App {

  def min(a: Int): Int = {
    if (a % 2 == 0) min(a / 2)
    else if (a % 3 == 0) min(a / 3)
    else a
  }

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).map(min)
  if (data.distinct.length == 1)
    println("Yes")
  else
    println("No")
}

object A573 {

  import IO._

  def gcd(a: Int, b: Int): Int = {
    if(b == 0) a else gcd(b, a%b)
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val g = in.foldLeft(in(0)){case (res, i) => gcd(res, i)}
    var break = false
    for(i <- 0 until n if !break) {
      var num = in(i)/g
      while(num%2 == 0) num /= 2
      while(num%3 == 0) num /= 3
      if(num != 1) {
        println("No")
        break = true
      }
    }
    if(!break) println("Yes")
  }

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

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

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

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

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

}

import scala.collection._

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

  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)

  val Array(n) = readInts(1)
  val as = readInts(n)

  val d = as.reduce(gcd)
  val ds = as.map(_ / d)

  var ok = true
  for (x <- ds) {
    var xx = x
    while ((xx & 1) == 0) xx >>= 1
    while (xx % 3 == 0) xx /= 3
    if (xx > 1) ok = false
  }

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


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data = in.next().split(" ").map(_.toLong)
  val answer = Array.ofDim[Long](n)
  answer(0) = Math.min(data.head, 1)
  Range(1, n).foreach(i => answer(i) = Math.min(data(i), answer(i - 1) + 1))
  answer(n - 1) = Math.min(data.last, 1)
  Range(n - 2, 0, -1).foreach(i => answer(i) = Math.min(answer(i), answer(i + 1) + 1))

  println(answer.max)
}

object Codeforces extends App {
  val in = new java.util.Scanner(System.in)
  var n = in.nextInt()
  var a = Array.ofDim[Int](n + 2)
  for (i <- 1 to n)
    a(i) = in.nextInt()
  a(0) = 0
  a(n + 1) = 0
  for (i <- 1 to n)
    a(i) = Math.min(a(i), a(i - 1) + 1)
  for (i <- n to 1 by -1)
    a(i) = Math.min(a(i), a(i + 1) + 1)
  var res = 0
  for (i <- 1 to n)
    res = Math.max(res, a(i))
  println(res)
}

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)
  val hs = readInts(n)

  val res = Array.ofDim[Int](n)

  var h = 0
  for (i <- hs.indices) {
    h = (h + 1) min hs(i)
    res(i) = h
  }

  h = 0
  for (i <- hs.indices.reverse) {
    h = (h + 1) min hs(i)
    res(i) = h min res(i)
  }

  println(res.max)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: IndexedSeq[Long] = in.next().split(" ").map(_.toLong).toIndexedSeq
  var sum = data.sum
  var j = 0
  if (data.min > (data.length + 1) / 2)
    println((data.length + 1) / 2)
  else
    while (sum > 0) {
      j += 1
      data = data.indices.map { i =>
        val ir =
          if (i > 0 && i < data.length - 1)
            Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
          else
            0
        sum += ir - data(i)
        ir
      }
      data = data.dropWhile(_ == 0).dropRight(1)
    }
  println(j)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Int] = in.next().split(" ").map(_.toInt)
  val data1: Array[Int] = data.clone()
  var left = 0
  var right = n - 1
  var sum = data.sum
  while (data(left) == 0 && left <= right)
    left += 1
  while (data(right) == 0 && right >= left)
    right -= 1
  var i = 0
//  println (sum)
  while (sum > 0) {
    i += 1
    sum -= data(left)
    sum -= data(right)
    data1(left) = 0
    data1(right) = 0
    Range(left + 1, right).foreach { i =>
      val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
      sum += ir - data(i)
      data(i) = ir
    }
    data = data1.clone()
//    println(sum)
//    println(data.mkString(" "))
    while (data(left) == 0 && left <= right)
      left += 1
    while (data(right) == 0 && right >= left)
      right -= 1
  }
  println(i + 1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Int] = in.next().split(" ").map(_.toInt)
  val data1: Array[Int] = data.clone()
  var sum = data.sum
//  println (sum)
  var j = 0
  while (sum > 0) {
    j += 1
    data.indices.foreach { i =>
      val ir =
        if (i > 0 && i < data.length - 1)
          Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
        else
          0
      sum += ir - data(i)
      data1(i) = ir
    }
    data = data1.clone()
  }
  println(j)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Int] = in.next().split(" ").map(_.toInt)
  val data1: Array[Int] = data.clone()
  var left = 0
  var right = n - 1
  var sum = data.sum
  while (data(left) == 0 && left < right)
    left += 1
  while (data(right) == 0 && right > left)
    right -= 1
  var i = 0
//  println (sum)
  while (sum > 0) {
    i += 1
    sum -= data(left)
    sum -= data(right)
    data1(left) = 0
    data1(right) = 0
    Range(left + 1, right).foreach { i =>
      val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
      sum += ir - data(i)
      data1(i) = ir
    }
    data = data1.clone()
    while (data(left) == 0 && left < right)
      left += 1
    while (data(right) == 0 && right > left)
      right -= 1
  }
  println(i)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Long] = in.next().split(" ").map(_.toLong)
  val data1: Array[Long] = data.clone()
  var sum = data.sum
//  println (sum)
  var j = 0
  while (sum > 0) {
    j += 1
    data.indices.foreach { i =>
      val ir =
        if (i > 0 && i < data.length - 1)
          Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
        else
          0
      sum -= ir + data(i)
      data1(i) = ir
    }
    data = data1.clone()
  }
  println(j)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data: Array[Int] = in.next().split(" ").map(_.toInt)
  val data1: Array[Int] = data.clone()
  var left = 0
  var right = n - 1
  var sum = data.sum
  while (data(left) == 0 && left <= right)
    left += 1
  while (data(right) == 0 && right >= left)
    right -= 1
  var i = 0
//  println (sum)
  while (sum > 0) {
    i += 1
    sum -= data(left)
    sum -= data(right)
    data1(left) = 0
    data1(right) = 0
    Range(left + 1, right).foreach { i =>
      val ir = Math.min(Math.min(Math.max(0, data(i) - 1), data(i - 1)), data(i + 1))
      sum += ir - data(i)
      data1(i) = ir
    }
    data = data1.clone()
    while (data(left) == 0 && left <= right)
      left += 1
    while (data(right) == 0 && right >= left)
      right -= 1
  }
  println(i)
}


object B extends App {

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

  val Array(n) = readInts(1)
  case class P(x: Int, y: Int)

  val obs = Array.fill(n) {
    val Array(x, y) = readInts(2)
    P(x, y)
  }

  val clues = Array.fill(n) {
    val Array(x, y) = readInts(2)
    P(x, y)
  }

  val oMinX = obs.map(_.x).min
  val oMinY = obs.map(_.y).min
  val cMaxX = clues.map(_.x).max
  val cMaxY = clues.map(_.y).max

  val tx = oMinX + cMaxX
  val ty = oMinY + cMaxY

  println(s"$tx $ty")
}

//package codeforces.contest1091

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object NewYearAndTheTreasureGeolocation {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readInt(): Int = {
    val st = new StringTokenizer(br.readLine())
    st.nextToken().toInt
  }

  def readLongPair(): (Long, Long) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toLong, st.nextToken.toLong)
  }

  def addIntPairs(p1: (Long, Long), p2: (Long, Long)): (Long, Long) = (p1._1 + p2._1, p1._2 + p2._2)

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val sum = (0 until 2 * n).foldLeft((0l, 0l))((acc, _) => addIntPairs(acc, readLongPair()))
    println(sum._1 / n + " " + sum._2 / n)
  }

}

object B extends App {

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

  val Array(n) = readInts(1)
  case class P(x: Int, y: Int)

  val obs = Array.fill(n) {
    val Array(x, y) = readInts(2)
    P(x, y)
  }

  val clues = Array.fill(n) {
    val Array(x, y) = readInts(2)
    P(x, y)
  }

  val cSet = clues.toSet

  for (c1 <- clues) {
    val tx = obs(0).x + c1.x
    val ty = obs(0).y + c1.y
    var i = 1
    while (i < n && cSet.contains(P(tx - obs(i).x, ty - obs(i).y))) {
      i += 1
    }
    if (i == n) {
      println(s"$tx $ty")
      System.exit(0)
    }
  }
}

//package codeforces.contest1091

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object NewYearAndTheTreasureGeolocation {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readInt(): Int = {
    val st = new StringTokenizer(br.readLine())
    st.nextToken().toInt
  }

  def readIntPair(): (Int, Int) = {
    val st = new StringTokenizer(br.readLine())
    (st.nextToken.toInt, st.nextToken.toInt)
  }

  def addIntPairs(p1: (Int, Int), p2: (Int, Int)): (Int, Int) = (p1._1 + p2._1, p1._2 + p2._2)

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val sum = (0 until 2 * n).foldLeft((0, 0))((acc, _) => addIntPairs(acc, readIntPair()))
    println(sum._1 / n + " " + sum._2 / n)
  }

}


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

/**
 * Created by arseny on 15.08.14.
 */
object C extends App {

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val k = nextInt
    val d = nextInt
    val ans = Array.fill(d, n)(1)
    def can(n: Int, k: Int, d: Int): Boolean = {
      if(k >= n) {
        true
      } else if(d == 1) {
        false
      } else {
        can((n.toDouble / k.toDouble).ceil.toInt, k, d - 1)
      }
    }
    if(!can(n, k, d)) {
      out.println(-1)
    } else {
      def fillAns(from: Int, to: Int, k: Int, d: Int): Unit = {
        //out.println(from, to, k, d)
        if(k >= to - from + 1) {
          for(i <- from to to) {
            ans(d - 1)(i) = i + 1  - from
          }
        } else {
          val g = ((to - from + 1).toDouble / k.toDouble).ceil.toInt
          for(i <- from to to) {
            ans(d - 1)(i) = (i - from) / g + 1
          }
          for(i <- from to to by g) {
            fillAns(i, math.min(i + g - 1, to), k, d - 1)
          }
        }
      }
      fillAns(0, n - 1, k, d)
      (0 until d).foreach{day =>
        out.println(ans(day).mkString(" "))
      }
    }
  }

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

}

object Main {

    def generate(n: Int, d: Int, m: Int): List[List[Int]] = {

        def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {

            def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {
                if (result.length >= n || value > m) {
                    return result
                } else {
                    return iterValue(value + 1,
                        iterPos(pos + 1, cur.+:(value), result))
                }
            }

            if (pos > d) {
                return result.+:(cur)
            } else {
                return iterValue(1, result)
            }

        }

        return iterPos(1, List[Int](), List[List[Int]]())

    }

    def transpose(mat: List[List[Int]]): List[List[Int]] = {
        def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {
            if (rem(0).isEmpty) {
                return result
            } else {
                return iter(rem.map(_.tail), result.+:(rem.map(_.head)))
            }
        }
        return iter(mat, List[List[Int]]())
    }

    def main(args: Array[String]) {
        val input = readLine().trim().split(" ").toList.map(_.toInt)
        val result = generate(input(0), input(2), input(1))
        if (result.length == input(0)) {
            transpose(result).foreach(entry => println(entry.mkString(" ")))
        } else {
            println(-1)
        }
    }

}

import java.math.BigInteger

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_3 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)

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

  val Array(n, k, d) = readInts(3)

  def nToBaseKWithDLen(n:Int):Array[Int] = {
    val res = Array.fill(d)(0)
    var curn = n
    var i = 0
    while(i < d) {
      res(i) = curn % k + 1
      curn = curn / k
      i = i + 1
    }
    res
  }

  val kbig = new BigInteger(k.toString)
  val dbig = new BigInteger(d.toString)
  val nbig = new BigInteger(n.toString)

  if(kbig.pow(d.toInt).compareTo(nbig) < 0){
    println(-1)
  } else {
    val solutions = (1 to n).map(nToBaseKWithDLen(_))
    for(day <- (1 to d)){
      println(solutions.map(_(day - 1)).mkString(" "))
    }
  }
}

object Main {

    def generate(n: Int, d: Int, m: Int): List[List[Int]] = {

        def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {

            def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {
                if (result.length >= n || value > m) {
                    return result
                } else {
                    return iterValue(value + 1,
                        iterPos(pos + 1, cur.+:(value), result))
                }
            }

            if (pos > d) {
                return result.+:(cur)
            } else {
                return iterValue(1, result)
            }

        }

        return iterPos(1, List[Int](), List[List[Int]]())

    }

    def transpose(mat: List[List[Int]]): List[List[Int]] = {
        def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {
            if (rem(0).isEmpty) {
                return result
            } else {
                return iter(rem.map(_.tail), result.+:(rem.map(_.head)))
            }
        }
        return iter(mat, List[List[Int]]())
    }

    def main(args: Array[String]) {
        val input = readLine().trim().split(" ").toList.map(_.toInt)
        val result = generate(input(0), input(2), input(1))
        if (result.length >= input(0)) {
            transpose(result.take(input(0))).foreach(entry => println(entry.mkString(" ")))
        } else {
            println(-1)
        }
    }

}

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

/**
 * Created by arseny on 15.08.14.
 */
object C extends App {

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val k = nextInt
    val d = nextInt
    val ans = Array.fill(d, n)(1)
    def can(n: Int, k: Int, d: Int): Boolean = {
      if(k >= n) {
        true
      } else if(d == 1) {
        false
      } else {
        can((n.toDouble / k.toDouble).ceil.toInt, k, d - 1)
      }
    }
    if(!can(n, k, d)) {
      out.println(-1)
    } else {
      def getAns(from: Int, to: Int, k: Int, d: Int): Unit = {
        if(k >= to - from + 1) {
          for(i <- from to to) {
            ans(d - 1)(i) = i + 1  - from
          }
        } else {
          val g = ((to - from + 1).toDouble / k.toDouble).ceil.toInt
          for(i <- from to to) {
            ans(d - 1)(i) = i / g + 1
          }
          for(i <- from to to by(k)) {
            getAns(i, math.min(i + k - 1, to), k, d - 1)
          }
        }
      }
      getAns(0, n - 1, k, d)
      (0 until d).foreach{day =>
        out.println(ans(day).mkString(" "))
      }
    }
  }

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

}

object Main {

    def generate(n: Int, d: Int, m: Int): List[List[Int]] = {

        def iterPos(pos: Int, cur: List[Int], result: List[List[Int]]): List[List[Int]] = {

            def iterValue(value: Int, result: List[List[Int]]): List[List[Int]] = {
                if (result.length >= n || value > m) {
                    return result
                } else {
                    return iterValue(value + 1,
                        iterPos(pos + 1, cur.+:(value), result))
                }
            }

            if (pos > d) {
                return result.+:(cur)
            } else {
                return iterValue(1, result)
            }

        }

        return iterPos(1, List[Int](), List[List[Int]]())

    }

    def transpose(mat: List[List[Int]]): List[List[Int]] = {
        def iter(rem: List[List[Int]], result: List[List[Int]]): List[List[Int]] = {
            if (rem(0).isEmpty) {
                return result
            } else {
                return iter(rem.map(_.tail), result.+:(rem.map(_.head)))
            }
        }
        return iter(mat, List[List[Int]]())
    }

    def main(args: Array[String]) {
        val input = readLine().trim().split(" ").toList.map(_.toInt)
        val result = generate(input(0), input(1), input(2))
        if (result.length >= input(0)) {
            transpose(result.take(input(0))).foreach(entry => println(entry.mkString(" ")))
        } else {
            println(-1)
        }
    }

}


import java.util.Scanner

object Main {

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

	def solve(): Unit = {
		val inp = new Scanner(System.in)
		val n = inp.nextInt()
		var cnt = 1
		inp.nextLine()
		(1 to n).foreach(_=>{
			val arr = new Array[Int](26)

			val s = inp.nextLine()
			for(i<- 1 until s.length){
				if(s.charAt(i)==s.charAt(i-1)){
					cnt+=1
				}else{
					if((cnt & 1) == 1){
						val c: Int = s.charAt(i-1) - 'a'
						arr(c) = 1
					}
					cnt = 1
				}
			}
			if((cnt & 1) == 1){
				val c: Int = s.charAt(s.length-1) - 'a'
				arr(c) = 1
			}
			cnt=1

			('a' to 'z').foreach(v=>{
				if(arr((v-'a')) == 1) print(v)
			})
			println()

		})

	}
}

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

object Main extends App {

  val n = readLine().toInt

  val alph = "qwertyuiopasdfghjklzxcvbnm"

  for(i <- 0 to n-1) {
    var st = readLine()
    for (i <- alph) {
      val pattern = i.toString + i.toString
      st = st.replaceAll(pattern, "-")
    }
    st = st.replaceAll("-", "")
    var set: mutable.TreeSet[String] = mutable.TreeSet()
    for (i <- st) {
      set += i.toString
    }
    val res = set.mkString
    println(res)
  }

}

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val s = ns()
      val ok = Array.ofDim[Boolean](26)
      var cnt = 0
      REP(s.length) { i =>
        if (i == 0 || s(i) == s(i - 1)) cnt += 1
        else {
          ok(s(i-1)-'a') |= cnt % 2 == 1
          cnt = 1
        }
      }
      ok(s.last-'a') |= cnt % 2 == 1
      REP(26) { i =>
        if (ok(i)) out.print(('a'+i).toChar)
      }
      out.println()
    }
  }
}

object KeyBoard extends App {

  val array = readFromTerminal()
  for (row <- array)
    println(compute(row))

  def readFromTerminal() = {
//    val n = 1
    val n = readInt()
//    val t = List("aadffgfd")
    val t: Seq[String] = for (i <- 1 to n) yield  readLine()
    t
  }

  def compute(row: String): String = {
    var mutable: Array[Char] = row.toCharArray
    var i = 1
    while (i < mutable.length) {
//      println(s"compare ${mutable(i - 1)} and ${mutable(i)}")
      if (mutable(i - 1) == mutable(i)) {
        mutable(i - 1) = 0
        mutable(i) = 0
      }
      i = i + 1
    }
    mutable.toSet.toList.sortWith(_.compareTo(_) < 0).mkString.trim
  }
}

object A1251 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer
  def check(str: String, char: Char): Boolean = {
    if (str.contains(char)) {
      var i = 0
      while (i < str.length && i != -1) {
        i = str.indexWhere(_ == char, i)
        if (i != -1) {
          val count = str.drop(i).takeWhile(_ == char).length
          if (count % 2 == 1)
            return true
          i += count
        }
      }
      false
    } else false
  }

  def main(args: Array[String]): Unit = {
    var t = readInt
    while (t > 0) {
      val str = read
      for (ch <- 'a' to 'z') {
        if (check(str, ch))
          out.print(ch)
      }
      out.println()
      t -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object _1251A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(implicit io: IO): io.type = repeat {
    val s = io.read[String]
    val good = splitRepeating(s).collect({case t if t.length.isOdd => t.head})
    io.writeAll(good.distinct.sorted, separator = "").writeLine()
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(implicit io: IO): io.type
  def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    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 {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    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.collection.mutable
import scala.io.StdIn._

object Main extends App {

  val n = readLine().toInt

  val alph = "qwertyuiopasdfghjklzxcvbnm"

  for(i <- 0 to n-1) {
    var st = readLine()
    for (i <- alph) {
      val pattern = i.toString + i.toString
      st = st.replaceAll(pattern, "")
    }
    var set: mutable.TreeSet[String] = mutable.TreeSet()
    for (i <- st) {
      set += i.toString
    }
    val res = set.mkString
    println(res)
  }

}

object _1251A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    repeat(io.read[Int]) {
      val s = io.read[String]
      val good = splitRepeating(s).collect({case t if t.length%2 == 1 => t.head})
      io.writeAll(good.sorted, separator = "").writeLine()
    }
    io
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object _1251A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    repeat(io.read[Int]) {
      val s = io.read[String]
      val good = splitRepeating(s).collect({case t if t.size == 1 => t.head})
      io.writeAll(good.sorted, separator = "").writeLine()
    }
    io
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


object B extends App {

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

  val Array(t) = readInts(1)

  for (_ <- 1 to t) {
    val Array(n) = readInts(1)
    val s = readLine
    val l = s.takeWhile(_ == '<').length
    val r = s.reverse.takeWhile(_ == '>').length
    println(l min r)
  }
  Console.flush
}

import scala.math._, scala.io.StdIn._

object Foo extends App {
  val t = readInt

  for (i <- 0 until t) {
    val n = readInt
    val s = readLine

    println(min(s.prefixLength(_=='<'),
                s.reverse.prefixLength(_=='>')))
  }

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

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val S = ns(N)

      var ans = 0
      val ix = S.lastIndexWhere(_ == '<')
      val ix2 = S.indexWhere(_ == '>')

      if (ix != -1 && ix2 != -1) {
        ans = min(N - 1 - ix, ix2)
      } else {
        ans = 0
      }

      out.println(ans)
    }
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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


object Main {
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val m = cin.nextInt()
    val n = cin.nextInt()
    var ans: Double = 0.0
    for (i <- 1 to m)
      ans += i * (Math.pow(i.toDouble / m, n) - Math.pow((i - 1.0) / m, n))
    println(ans)
  }
}

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

/**
 * Created by arseny on 01.08.14.
 */
object C extends App {

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val m = nextDouble
    val n = nextDouble
    if (m == 1) {
      out.println(1)
    } else {
      var ans = m
      for (i <- 1 to (m - 1).toInt) {
        val p = i.toDouble / m
        val q = math.pow(p, n)
        ans = ans - q
      }
      out.println("%.6f".format(ans))
    }
  }

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

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object C extends App {

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

  val Array(m, n) = readInts(2)

  val mn = math.pow(m.toDouble, n)
  var sum = 0d
  var prevCount = 0d
  for (i <- 1 to m) {
    val count = math.pow(i.toDouble / m.toDouble, n)
    //println(sum, count, i)
    sum += (count - prevCount) * i
    prevCount = count// - prevCount
  }

  println(sum)
}

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

object C {

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

  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 solve: Int = {
    val m = nextInt
    val n = nextInt
    var ans: Double = m.toDouble
    for (i <- 0 to m - 1) {
      ans -= Math.pow(i.toDouble / m.toDouble, n)
    }
    out.println(ans)
    return 1
  }

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

import scala.io.StdIn._

object Main {

  def power(a: Double, n: Int): Double = {
    var ans = 1.0
    var b = a
    var p = n
    while (p > 0) {
      if ( (p & 0x01) != 0) ans = b * ans
      b = b * b
      p = p >> 1;
    }
    ans
  }
  def main(args: Array[String]): Unit = {
    val mn = readLine.split(" ").map(_.toInt)
    val m = mn.head
    val n = mn.last
    val ans = (1 to m).map { k =>
      k * (power((k*1.0)/m, n) - power(((k*1.0) - 1.0)/m, n))
    }.sum
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val m = cin.nextInt()
    val n = cin.nextInt()
    def solve(i: Int, res: Double):Double =
      if (i == 0) res
      else solve(i - 1, res + i * (Math.pow((1.0 * i) / m, n) - Math.pow((i - 1.0) / m, n)))
    println(solve(m, 0))
  }
}

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

object C {

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

  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 solve: Int = {
    val m = nextInt
    val n = nextInt
    var ans: Double = 0.0d
    val delimeter: Double = Math.pow(m, n)
    for (i <- 1 to m) {
      ans += Math.pow(i.toDouble, n + 1) - Math.pow(i - 1, n) * i.toDouble
    }
    out.println(ans / delimeter)
    return 1
  }

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