Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.  The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of disks on the combination lock. The second line contains a string of n digits — the original state of the disks. The third line contains a string of n digits — Scrooge McDuck's combination that opens the lock.

Print a single integer — the minimum number of moves Scrooge McDuck needs to open the lock.

NoteIn the sample he needs 13 moves:  1 disk:   2 disk:   3 disk:   4 disk:   5 disk:

import scala.io.StdIn._

object Main extends App {
  readInt()
  val a = readLine().map(_.asDigit)
  val b = readLine().map(_.asDigit)
  val ans = a.zip(b).map { case (x, y) => val d = (x - y).abs; d min (10 - d) }.sum
  println(ans)
}

object Solve extends App with fastIO{
  val n = nextInt
  val cur = next.map(_.toString.toInt)
  val res = next.map(_.toString.toInt)

  println(
    (for(i <- 0 until n) yield Math.min(Math.min(Math.abs(cur(i)-res(i)), Math.abs((cur(i)+res(i)))),
    Math.min(Math.abs(10+cur(i)-res(i)),Math.abs(10+res(i)-cur(i))))).sum
  )

  flush
}

trait fastIO {
  import java.io._
  val isFile = false
  val input = "file.in"
  val output = "file.out"
  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }
  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }
  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }
  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }
  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object main{
  object Solver extends InputReader{
    def solve(){
      val n = getInt()
      val a = getStr()
      val b = getStr()

      val diffs = for(i <- 0 to n - 1) yield {
        val aa = a(i)
        val bb = b(i)
        val diff: Int = Math.abs(aa - bb)
        diff min 10 - diff
      }

      println(diffs.sum)
    }
  }

  // TEMPLATE ------------------------

  def main(args: Array[String]){
    Solver.solve()
  }

  trait InputReader{
    import java.io._
    import java.util._
    protected val stream = System.in
    private val reader = new BufferedReader(new InputStreamReader(stream))
    private var tokenizer = new StringTokenizer(reader.readLine())

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

    def getInt(): Int = getStr().toInt
    def getLong(): Long = getStr().toLong
    def getDouble(): Double = getStr().toDouble
  }
}

import java.util.StringTokenizer

object _540 extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = next
  val b = next
  val ans = (0 until n).map(i => { val diff = (0 + a(i) - b(i)).abs; diff min (10 - diff) }).sum
  println(ans)
}

object A540 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input1 = scala.io.StdIn.readLine
    val input2 = scala.io.StdIn.readLine
    var res = 0
    for(i <- 0 until n) {
      res += math.min(math.abs(input1(i) - input2(i)), if(input1(i) > input2(i)) 10 - input1(i) + input2(i) else 10 - input2(i) + input1(i)  )
    }
    println(res)
  }
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import Ordering.Implicits._

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def cost(a: Int, b: Int) = math.min(math.abs(a - b), 10 - math.abs(a - b))

  def cost(p: (Char, Char)): Int = cost(p._1.toInt, p._2.toInt)

  def solve(): Unit = {
    val n = nextInt
    val srcs: String = next
    val dest: String = next
    out.println((srcs zip dest).foldLeft(0)(_  + cost(_)))
  }

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

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

import scala.collection.mutable

object A {

  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 n = nextInt
    val s1 = next.toCharArray
    val s2 = next.toCharArray
    var res = 0
    for (i <- 0 until n) {
      if (s1(i) != s2(i)) {
        val x1 = Math.max(s1(i), s2(i)) - 48
        val x2 = Math.min(s1(i), s2(i)) - 48
        res += Math.min(x1 - x2, x2 - x1 + 10)
      }
    }
    out.println(res)
    return 0
  }
}

// http://codeforces.com/contest/540/submission/10942295
object Test2A540 extends App {
  import java.util.Scanner

  type Input = (Seq[(Int, Int)])
  type Output = Int

  def read(scanner: Scanner): Input = {
    import scanner._
    nextInt
    nextLine
    val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})
    src zip target
  }

  def solve(problem: Input): Output = {
    problem map { case (a, b) =>
      val (x, y) = if (a < b) (a, b) else (b, a)
      val l = (y - x).abs
      val r = x + (10 - y)
      l min r
    } sum
  }

  def format(result: Output): String = result.toString

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

// http://codeforces.com/contest/540/submission/10942295
object TestA540 extends App {
  import java.util.Scanner

  type Input = (Seq[(Int, Int)])
  type Output = Int

  def read(scanner: Scanner): Input = {
    import scanner._
    nextInt
    nextLine
    val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})
    src zip target
  }

  def solve(problem: Input): Output = {
    problem map { case (a, b) =>
      val (x, y) = if (a < b) (a, b) else (b, a)
      val l = (y - x).abs
      val r = x + (10 - y)
      l min r
    } sum
  }

  def format(result: Output): String = result.toString

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object A540 extends App {
  import java.util.Scanner

  type Input = (Seq[(Int, Int)])
  type Output = Int

  def read(scanner: Scanner): Input = {
    import scanner._
    nextInt
    nextLine
    val (src, target) = (nextLine map {_ - '0'}, nextLine map {_ - '0'})
    src zip target
  }

  def solve(problem: Input): Output = {
    problem map { case (a, b) =>
      val (x, y) = if (a < b) (a, b) else (b, a)
      val l = (y - x).abs
      val r = x + (10 - y)
      l min r
    } sum
  }

  def format(result: Output): String = result.toString

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

import scala.io.StdIn._

object A extends App {
  readInt()
  val start = readLine().map(_.toString.toInt)
  val end = readLine().map(_.toString.toInt)

  def diff(ss: Int, tt: Int): Int = {
    val s = Math.min(ss, tt)
    val t = Math.max(ss, tt)

    val p1 = Math.abs(s - t)
    val p2 = Math.abs(s + 10 - t)
    Math.min(p1, p2)
  }

  def solve(s: Seq[Int], t: Seq[Int]): Int = {
    var sum = 0
    for (i <- 0 until s.length) {
      sum += diff(s(i), t(i))
    }
    sum
  }

  println(solve(start, end))

}

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

import Math.min
import Math.abs

object CombinationLock {

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

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

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

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

   def main(args: Array[String]) {
     val n = readInt
     val now = readLine.map(_.toInt)
     val secret = readLine.map(_.toInt)
     println(now.zip(secret).foldLeft(0)
         { case (t, (n,s)) => t + min(abs(n-s),10-abs(n-s))})
   }

}

/**
 * Created by przemek on 30.04.15.
 */
object A extends App  {

  def solve(state: Array[Int], comb: Array[Int]): Int = {
    var sum = 0
    for ((s, k) <- state.zip(comb)) {
      val m = math.min(math.abs(s-k),math.min(10-k+s, 10-s+k))
      sum += m
    }
    sum
  }

  val L = readLine()
  val state = readLine().toCharArray().map(_.toInt)
  val comb = readLine().toCharArray().map(_.toInt)

  println(solve(state, comb))

}

import Array._

object main extends App with fastIO {

  var Array(n) = readLine split(" ") map(_.toInt)
  println(readLine.map(_ - '0').zip(readLine map(_ - '0'))
      .foldLeft(0)((s, v) => s + ((v._1 - v._2).abs min (10 - (v._1 - v._2).abs))))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}


It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) — one ant in each direction. No other ant movements will happen. Ants never interfere with each other.Scientists have put a colony of n ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.

First input line contains integers n (0 ≤ n ≤ 30000) and t (1 ≤ t ≤ 50000), where n is the number of ants in the colony and t is the number of queries. Each of the next t lines contains coordinates of a query junction: integers xi, yi ( - 109 ≤ xi, yi ≤ 109). Queries may coincide. It is guaranteed that there will be a certain moment of time when no possible movements can happen (in other words, the process will eventually end).

Print t integers, one per line — the number of ants at the corresponding junctions when the movement of the ants stops.

NoteIn the first sample the colony consists of the one ant, so nothing happens at all.In the second sample the colony consists of 6 ants. At the first minute 4 ants scatter from (0, 0) to the neighbouring junctions. After that the process stops.

import java.util

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, T = ni()

//    val W = 5
    val W = 80
    val Width = W
    val MAX = Width * Width

    val g = Array.ofDim[Int](MAX)
    val set = new util.BitSet(MAX)

    case class Coord(x: Int, y: Int)
    val D = Array(Coord(1, 0), Coord(-1, 0),  Coord(0, 1), Coord(0, -1))

    g(0) = N

    var cnt = 0

//    var i = 0
    set.set(0)
    var v = set.nextSetBit(0)
    while(v != -1) {
      if (g(v) >= 4) {
        cnt += 1
        val q = g(v) / 4

        g(v) -= q * 4

        val x = v / Width
        val y = v % Width

        REP(4) { i =>
          val d = D(i)
          if (x + d.x >= 0 && y + d.y >= 0) {
            val toXAxis = x + d.x == 0 && d.x == -1
            val toYAxis = y + d.y == 0 && d.y == -1
            val mult =
              if (toXAxis) 2
              else if (toYAxis) 2
              else if (toXAxis && toYAxis) 4
              else 1

            val next = (x + d.x) * Width + y + d.y
            g(next) += q * mult
            set.set(next)
          }
        }
      }

      set.clear(v)
      v = set.nextSetBit(v + 1)
      if (v == -1) v = set.nextSetBit(0)
    }

    System.err.println(cnt)
//    System.err.println(i)

    def sum = {
      val zero = g(0)

      val axis = map(MAX)(identity).filter { v =>
        v != 0 && (v % Width == 0 || v / Width == 0)
      }.map(g).sum

      val other = map(MAX)(identity).filter { v =>
        v % Width > 0 && v / Width > 0
      }.map(g).sum
      zero + axis * 2 + other * 4
    }

//    assert(sum == N)

    REP(T) { _ =>
      val x, y = ni()
      if (x > -W && x < W && y > -W && y < W) {
        val v = abs(x) * Width + abs(y)
        out.println(g(v))
      } else {
        out.println(0)
      }
    }
  }

  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 java.util

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, T = ni()

//    val W = 5
    val W = 80
    val Width = W
    val MAX = Width * Width

    val g = Array.ofDim[Int](MAX)
    val set = Array.fill(2)(new util.BitSet(MAX))

    case class Coord(x: Int, y: Int)
    val D = Array(Coord(1, 0), Coord(-1, 0),  Coord(0, 1), Coord(0, -1))

    g(0) = N

    var cnt = 0

    var i = 0
    set(0).set(0)
    while(set(i % 2).cardinality() > 0) {
      val ii = i % 2
      set(ii ^ 1).clear()
      var v = set(ii).nextSetBit(0)
      while(v != -1) {
        if (g(v) >= 4) {
          cnt += 1
          val q = g(v) / 4

          g(v) -= q * 4

          val x = v / Width
          val y = v % Width

          REP(4) { i =>
            val d = D(i)
            if (x + d.x >= 0 && y + d.y >= 0) {
              val toXAxis = x + d.x == 0 && d.x == -1
              val toYAxis = y + d.y == 0 && d.y == -1
              val mult =
                if (toXAxis) 2
                else if (toYAxis) 2
                else if (toXAxis && toYAxis) 4
                else 1

              val next = (x + d.x) * Width + y + d.y
              g(next) += q * mult
              set(ii ^ 1).set(next)
            }
          }
        }

        v = set(ii).nextSetBit(v + 1)
      }
      i += 1
    }

    System.err.println(cnt)
    System.err.println(i)

    def sum = {
      val zero = g(0)

      val axis = map(MAX)(identity).filter { v =>
        v != 0 && (v % Width == 0 || v / Width == 0)
      }.map(g).sum

      val other = map(MAX)(identity).filter { v =>
        v % Width > 0 && v / Width > 0
      }.map(g).sum
      zero + axis * 2 + other * 4
    }

//    assert(sum == N)

    REP(T) { _ =>
      val x, y = ni()
      if (x > -W && x < W && y > -W && y < W) {
        val v = abs(x) * Width + abs(y)
        out.println(g(v))
      } else {
        out.println(0)
      }
    }
  }

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


Polycarp lives on the coordinate axis $$$Ox$$$ and travels from the point $$$x=a$$$ to $$$x=b$$$. It moves uniformly rectilinearly at a speed of one unit of distance per minute.On the axis $$$Ox$$$ at the point $$$x=c$$$ the base station of the mobile operator is placed. It is known that the radius of its coverage is $$$r$$$. Thus, if Polycarp is at a distance less than or equal to $$$r$$$ from the point $$$x=c$$$, then he is in the network coverage area, otherwise — no. The base station can be located both on the route of Polycarp and outside it.Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from $$$x=a$$$ to $$$x=b$$$. His speed — one unit of distance per minute.

The first line contains a positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. In the following lines are written $$$t$$$ test cases. The description of each test case is one line, which contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$r$$$ ($$$-10^8 \le a,b,c \le 10^8$$$, $$$0 \le r \le 10^8$$$) — the coordinates of the starting and ending points of the path, the base station, and its coverage radius, respectively. Any of the numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (either any pair or all three numbers). The base station can be located both on the route of Polycarp and outside it.

Print $$$t$$$ numbers — answers to given test cases in the order they are written in the test. Each answer is an integer — the number of minutes during which Polycarp will be unavailable during his movement.

NoteThe following picture illustrates the first test case.     Polycarp goes from $$$1$$$ to $$$10$$$. The yellow area shows the coverage area of the station with a radius of coverage of $$$1$$$, which is located at the point of $$$7$$$. The green area shows a part of the path when Polycarp is out of coverage area.

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("MY_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = {
    if (!oj){ System.err.println(s) }
  }
  def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      var a, b = ni()
      if (a > b) {
        val t = a
        a = b
        b = t
      }
      val c, R = ni()
      val l = c - R
      val r = c + R
      val cover = max(0, min(b, r) - max(a, l))
      val n = b - a
      val ans = n - cover
      out.println(ans)
    }
  }
}


You are playing a very popular computer game. The next level consists of $$$n$$$ consecutive locations, numbered from $$$1$$$ to $$$n$$$, each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also, if you become inside a location with water, you will die, so you can only move between locations with land.You can jump between adjacent locations for free, as well as no more than once jump from any location with land $$$i$$$ to any location with land $$$i + x$$$, spending $$$x$$$ coins ($$$x \geq 0$$$).Your task is to spend the minimum possible number of coins to move from the first location to the last one.Note that this is always possible since both the first and last locations are the land locations.

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of locations. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), where $$$a_i = 1$$$ means that the $$$i$$$-th location is the location with land, and $$$a_i = 0$$$ means that the $$$i$$$-th location is the location with water. It is guaranteed that $$$a_1 = 1$$$ and $$$a_n = 1$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the first test case, it is enough to make one free jump from the first location to the second one, which is also the last one, so the answer is $$$0$$$.In the second test case, the only way to move from the first location to the last one is to jump between them, which will cost $$$4$$$ coins.In the third test case, you can jump from the first location to the third for $$$2$$$ coins, and then jump to the fourth location for free, so the answer is $$$2$$$. It can be shown that this is the optimal way.

import scala.io.StdIn.readLine

object Solution {

  def coins() = {
    val nodes = readLine.toInt
    val nodeList = readLine.split("\\s+")

    val first = nodeList.indexOf("0")
    val last = nodeList.length - 1 - nodeList.reverse.indexOf("0")

    if (first == -1) 0
    else if (first == last) 2
    else last - first + 2
  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt
    for (
      i <- 0 until cases
    ) println(coins())
  }
}


Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 106). The second line contains a string s of length n, consisting of lowercase English letters.

If there is no string satisfying the given conditions then print "-1" (without the quotes). Otherwise, print any nice string s' that .

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val str = in.next()
  val result = Array.ofDim[Char](n)
  val (good, left) = str.indices.foldLeft(true, k) {
    case(acc@(false, _), i) => acc
    case(acc@(_, 0), i) =>
      result(i) = str(i)
      acc
    case((_, left), i) if str(i) - 'a' >= 'z' - str(i) =>
      val minus = Math.min(str(i) - 'a', left)
      result(i) = (str(i) - minus).toChar
      (true, left - minus)
    case((_, left), i) =>
      val minus = Math.min('z' - str(i), left)
      result(i) = (str(i) + minus).toChar
      (true, left - minus)
  }
  if (good && left == 0)
    println(result.mkString)
  else
    println(-1)
}


Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed.After some time, the wise men returned from the trip even wiser. They locked up for six months in the dining room, after which they said to the king: "there are a lot of different languages, but almost all of them have letters that are divided into vowels and consonants; in a word, vowels and consonants must be combined correctly."There are very many rules, all of them have exceptions, but our language will be deprived of such defects! We propose to introduce a set of formal rules of combining vowels and consonants, and include in the language all the words that satisfy them.The rules of composing words are: The letters are divided into vowels and consonants in some certain way; All words have a length of exactly n; There are m rules of the form (pos1, t1, pos2, t2). Each rule is: if the position pos1 has a letter of type t1, then the position pos2 has a letter of type t2.You are given some string s of length n, it is not necessarily a correct word of the new language. Among all the words of the language that lexicographically not smaller than the string s, find the minimal one in lexicographic order.

The first line contains a single line consisting of letters 'V' (Vowel) and 'C' (Consonant), determining which letters are vowels and which letters are consonants. The length of this string l is the size of the alphabet of the new language (1 ≤ l ≤ 26). The first l letters of the English alphabet are used as the letters of the alphabet of the new language. If the i-th character of the string equals to 'V', then the corresponding letter is a vowel, otherwise it is a consonant. The second line contains two integers n, m (1 ≤ n ≤ 200, 0 ≤ m ≤ 4n(n - 1)) — the number of letters in a single word and the number of rules, correspondingly. Next m lines describe m rules of the language in the following format: pos1, t1, pos2, t2 (1 ≤ pos1, pos2 ≤ n, pos1 ≠ pos2,  'V', 'C' }). The last line contains string s of length n, consisting of the first l small letters of the English alphabet. It is guaranteed that no two rules are the same.

Print a smallest word of a language that is lexicographically not smaller than s. If such words does not exist (for example, if the language has no words at all), print "-1" (without the quotes).

NoteIn the first test word "aa" is not a word of the language, but word "ab" is.In the second test out of all four possibilities only word "bb" is not a word of a language, but all other words are lexicographically less, so there is no answer.In the third test, due to the last rule, "abac" doesn't belong to the language ("a" is a vowel, "c" is a consonant). The only word with prefix "ab" that meets the given rules is "abaa". But it is less than "abac", so the answer will be "acaa"

import scala.collection.mutable.BitSet

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a = in(0).toInt - 1
    val b = in(2).toInt - 1

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a) += b
        vToV(b) += a
      case ('V', 'C') =>
        vToC(a) += b
        vToC(b) += a
      case ('C', 'V') =>
        cToV(a) += b
        cToV(b) += a
      case ('V', 'V') =>
        vToV(a) += b
        cToC(b) += a
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j))
        cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))
        vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))
        vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))
      }
    }
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone

  def isValidPrefix(prefixLen: Int): Boolean = {

    val isSetToC, isSetToV = Array.fill(n) { false }

    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }

    for (i <- 0 until prefixLen) {
      if (isSetToC(i)) {
        for (j <- 0 until n) {
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else if (isSetToV(i)) {
        for (j <- 0 until n) {
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    true
  }

  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) {
                maxValidPrefixLen = prefixLen
                checkedV = true
              }
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) {
                maxValidPrefixLen = prefixLen
                checkedC = true
              }
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
          }
        }
      }
    }

    if (isValidPrefix(n)) println(s.map(c => (c + 'a').toChar).mkString)
    else println(-1)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import scala.collection.mutable.Stack

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  def vert(i: Int) = if (i < 0) n - i else i
  def vertNot(i: Int) = vert(-i)

  val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a0 = in(0).toInt - 1
    val b0 = in(2).toInt - 1
    val a = (a0 + 1) * (if (isC(c1)) 1 else -1)
    val b = (b0 + 1) * (if (isC(c2)) 1 else -1)
    // implication (a -> b)
    adjBuilders(vert(a)) += vert(b)
    adjBuilders(vertNot(b)) += vertNot(a)
    revBuilders(vert(b)) += vert(a)
    revBuilders(vertNot(a)) += vertNot(b)

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a0) += b0
        vToV(b0) += a0
      case ('V', 'C') =>
        vToC(a0) += b0
        vToC(b0) += a0
      case ('C', 'V') =>
        cToV(a0) += b0
        cToV(b0) += a0
      case ('V', 'V') =>
        vToV(a0) += b0
        cToC(b0) += a0
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j))
        cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))
        vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))
        vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))
      }
    }
  }

  val adj = adjBuilders.map(_.result)
  val rev = revBuilders.map(_.result)

  def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {

    val visited1 = new BitSet(2 * n + 1)
    val stack = Stack.empty[Int]

    def dfs1(u: Int): Unit = {
      if (!visited1(u)) {
        visited1 += u
        for (v <- rev(u)) dfs1(v)
        stack.push(u)
      }
    }

    for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack

    val visited2 = new BitSet(2 * n + 1)
    val sccNums = Array.ofDim[Int](2 * n + 1)

    def dfs2(u: Int, lead: Int): Unit = {
      if (!visited2(u)) {
        visited2 += u
        sccNums(u) = lead
        for (v <- adj(u)) dfs2(v, lead)
      }
    }

    while (stack.nonEmpty) {
      val lead = stack.pop()
      dfs2(lead, lead)
    }

    sccNums
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val sccNums = sat2(n, adj, rev)
  val sccCount = sccNums.length
  val sccUtil = Array.fill(sccCount) { 0 }

  for (i <- s.indices) {
    val cc = (i + 1) * (if (isC(s(i))) 1 else -1)
    sccUtil(sccNums(vert(cc))) += 1
  }

  def isValidPrefix(prefixLen: Int): Boolean = {
    val isSetToC, isSetToV = Array.fill(n) { false }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }
   // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)
   // println(isSetToC.mkString, isSetToV.mkString)
    for (i <- 0 until prefixLen) {
      if (isSetToC(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'C')
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else if (isSetToV(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'V')
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    for (i <- prefixLen + 1 until n) {
      val cc = (i + 1)
      //if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false
    }
    true
  }
//println(vToC(0))
//println(cToV(0))
  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) {
                maxValidPrefixLen = prefixLen
                checkedV = true
              }
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) {
                maxValidPrefixLen = prefixLen
                checkedC = true
              }
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
            //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
            //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        }
      }
    }

    if (isValidPrefix(n)) println(s.map(c => (c + 'a').toChar).mkString)
    else println(-1)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a = in(0).toInt - 1
    val b = in(2).toInt - 1

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a) += b
        vToV(b) += a
      case ('V', 'C') =>
        vToC(a) += b
        vToC(b) += a
      case ('C', 'V') =>
        cToV(a) += b
        cToV(b) += a
      case ('V', 'V') =>
        vToV(a) += b
        cToC(b) += a
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j))
        cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))
        vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))
        vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))
      }
    }
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val isSetToC, isSetToV = Array.ofDim(n)

  def isValidPrefix(prefixLen: Int): Boolean = {

    val isSetToC, isSetToV = Array.fill(n) { false }

    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }

    for (i <- 0 until prefixLen) {
      if (isSetToC(i)) {
        for (j <- 0 until n) {
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else if (isSetToV(i)) {
        for (j <- 0 until n) {
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    true
  }

  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) {
                maxValidPrefixLen = prefixLen
                checkedV = true
              }
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) {
                maxValidPrefixLen = prefixLen
                checkedC = true
              }
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
          }
        }
      }
    }

    if (isValidPrefix(n)) println(s.map(c => (c + 'a').toChar).mkString)
    else println(-1)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import scala.collection.mutable.Stack

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  def vert(i: Int) = if (i < 0) n - i else i
  def vertNot(i: Int) = vert(-i)

  val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a0 = in(0).toInt - 1
    val b0 = in(2).toInt - 1
    val a = (a0 + 1) * (if (isC(c1)) 1 else -1)
    val b = (b0 + 1) * (if (isC(c2)) 1 else -1)
    // implication (a -> b)
    adjBuilders(vert(a)) += vert(b)
    adjBuilders(vertNot(b)) += vertNot(a)
    revBuilders(vert(b)) += vert(a)
    revBuilders(vertNot(a)) += vertNot(b)

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a0) += b0
        vToV(b0) += a0
      case ('V', 'C') =>
        vToC(a0) += b0
        vToC(b0) += a0
      case ('C', 'V') =>
        cToV(a0) += b0
        cToV(b0) += a0
      case ('V', 'V') =>
        vToV(a0) += b0
        cToC(b0) += a0
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j))
        cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))
        vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))
        vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))
      }
    }
  }

  val adj = adjBuilders.map(_.result)
  val rev = revBuilders.map(_.result)

  def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {

    val visited1 = new BitSet(2 * n + 1)
    val stack = Stack.empty[Int]

    def dfs1(u: Int): Unit = {
      if (!visited1(u)) {
        visited1 += u
        for (v <- rev(u)) dfs1(v)
        stack.push(u)
      }
    }

    for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack

    val visited2 = new BitSet(2 * n + 1)
    val sccNums = Array.ofDim[Int](2 * n + 1)

    def dfs2(u: Int, lead: Int): Unit = {
      if (!visited2(u)) {
        visited2 += u
        sccNums(u) = lead
        for (v <- adj(u)) dfs2(v, lead)
      }
    }

    while (stack.nonEmpty) {
      val lead = stack.pop()
      dfs2(lead, lead)
    }

    sccNums
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val sccNums = sat2(n, adj, rev)
  val sccCount = sccNums.length
  val sccUtil = Array.fill(sccCount) { 0 }

  for (i <- s.indices) {
    val cc = (i + 1) * (if (isC(s(i))) 1 else -1)
    sccUtil(sccNums(vert(cc))) += 1
  }

  def isValidPrefix(prefixLen: Int): Boolean = {
    val isSetToC, isSetToV = Array.fill(n) { false }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }
   // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)
   // println(isSetToC.mkString, isSetToV.mkString)
    for (i <- 0 until prefixLen) {
      if (isC(s(i))) {
        for (j <- 0 until n) {
          //println(i, j, 'C')
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else { // !isC(s(i))
        for (j <- 0 until n) {
          //println(i, j, 'V')
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    for (i <- prefixLen + 1 until n) {
      val cc = (i + 1)
      if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false
    }
    true
  }
//println(vToC(0))
//println(cToV(0))
  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
            //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
            //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        }
      }
    }

    println(s.map(c => (c + 'a').toChar).mkString)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import scala.collection.mutable.Stack

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  def vert(i: Int) = if (i < 0) n - i else i
  def vertNot(i: Int) = vert(-i)

  val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a0 = in(0).toInt - 1
    val b0 = in(2).toInt - 1
    val a = (a0 + 1) * (if (isC(c1)) 1 else -1)
    val b = (b0 + 1) * (if (isC(c2)) 1 else -1)
    // implication (a -> b)
    adjBuilders(vert(a)) += vert(b)
    adjBuilders(vertNot(b)) += vertNot(a)
    revBuilders(vert(b)) += vert(a)
    revBuilders(vertNot(a)) += vertNot(b)

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a0) += b0
      //vToV(b0) += a0
      case ('V', 'C') =>
        vToC(a0) += b0
      //vToC(b0) += a0
      case ('C', 'V') =>
        cToV(a0) += b0
      //cToV(b0) += a0
      case ('V', 'V') =>
        vToV(a0) += b0
      //cToC(b0) += a0
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= cToC(i)(k) && cToC(k)(j)
        cToV(i)(j) |= cToV(i)(k) && cToV(k)(j)
        vToC(i)(j) |= vToC(i)(k) && vToC(k)(j)
        vToV(i)(j) |= vToV(i)(k) && vToV(k)(j)
      }
    }
  }

  val adj = adjBuilders.map(_.result)
  val rev = revBuilders.map(_.result)

  def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {

    val visited1 = new BitSet(2 * n + 1)
    val stack = Stack.empty[Int]

    def dfs1(u: Int): Unit = {
      if (!visited1(u)) {
        visited1 += u
        for (v <- rev(u)) dfs1(v)
        stack.push(u)
      }
    }

    for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack

    val visited2 = new BitSet(2 * n + 1)
    val sccNums = Array.ofDim[Int](2 * n + 1)

    def dfs2(u: Int, lead: Int): Unit = {
      if (!visited2(u)) {
        visited2 += u
        sccNums(u) = lead
        for (v <- adj(u)) dfs2(v, lead)
      }
    }

    while (stack.nonEmpty) {
      val lead = stack.pop()
      dfs2(lead, lead)
    }

    sccNums
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val sccNums = sat2(n, adj, rev)
  val sccCount = sccNums.length
  val sccUtil = Array.fill(sccCount) { 0 }

  for (i <- s.indices) {
    val cc = (i + 1) * (if (isC(s(i))) 1 else -1)
    sccUtil(sccNums(vert(cc))) += 1
  }

  def isValidPrefix(prefixLen: Int): Boolean = {
    val isSetToC, isSetToV = Array.fill(n) { false }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      if (isC(c)) {
        for (b <- 0 until n) {
          if (cToC(i)(b)) if (isSetToV(b)) return false
          else isSetToC(b) = true
          if (cToV(i)(b)) if (isSetToC(b)) return false
          else isSetToV(b) = true
        }
      } else {
        for (b <- 0 until n) {
          if (vToC(i)(b)) if (isSetToV(b)) return false
          else isSetToC(b) = true
          if (vToV(i)(b)) if (isSetToC(b)) return false
          else isSetToV(b) = true
        }
      }
    }
    for (i <- prefixLen + 1 until n) {
      val cc = (i + 1)
      if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false
    }
    true
  }

  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
          }
        }
      }
    }

    println(s.map(c => (c + 'a').toChar).mkString)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import scala.collection.mutable.Stack

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  def vert(i: Int) = if (i < 0) n - i else i
  def vertNot(i: Int) = vert(-i)

  val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a0 = in(0).toInt - 1
    val b0 = in(2).toInt - 1
    val a = (a0 + 1) * (if (isC(c1)) 1 else -1)
    val b = (b0 + 1) * (if (isC(c2)) 1 else -1)
    // implication (a -> b)
    adjBuilders(vert(a)) += vert(b)
    adjBuilders(vertNot(b)) += vertNot(a)
    revBuilders(vert(b)) += vert(a)
    revBuilders(vertNot(a)) += vertNot(b)

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a0) += b0
      //vToV(b0) += a0
      case ('V', 'C') =>
        vToC(a0) += b0
      //vToC(b0) += a0
      case ('C', 'V') =>
        cToV(a0) += b0
      //cToV(b0) += a0
      case ('V', 'V') =>
        vToV(a0) += b0
      //cToC(b0) += a0
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
//        cToC(i)(j) |= cToC(i)(k) && cToC(k)(j)
//        cToV(i)(j) |= cToV(i)(k) && cToV(k)(j)
//        vToC(i)(j) |= vToC(i)(k) && vToC(k)(j)
//        vToV(i)(j) |= vToV(i)(k) && vToV(k)(j)
      }
    }
  }

  val adj = adjBuilders.map(_.result)
  val rev = revBuilders.map(_.result)

  def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {

    val visited1 = new BitSet(2 * n + 1)
    val stack = Stack.empty[Int]

    def dfs1(u: Int): Unit = {
      if (!visited1(u)) {
        visited1 += u
        for (v <- rev(u)) dfs1(v)
        stack.push(u)
      }
    }

    for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack

    val visited2 = new BitSet(2 * n + 1)
    val sccNums = Array.ofDim[Int](2 * n + 1)

    def dfs2(u: Int, lead: Int): Unit = {
      if (!visited2(u)) {
        visited2 += u
        sccNums(u) = lead
        for (v <- adj(u)) dfs2(v, lead)
      }
    }

    while (stack.nonEmpty) {
      val lead = stack.pop()
      dfs2(lead, lead)
    }

    sccNums
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val sccNums = sat2(n, adj, rev)
  val sccCount = sccNums.length
  val sccUtil = Array.fill(sccCount) { 0 }

  for (i <- s.indices) {
    val cc = (i + 1) * (if (isC(s(i))) 1 else -1)
    sccUtil(sccNums(vert(cc))) += 1
  }

  def isValidPrefix(prefixLen: Int): Boolean = {
    val isSetToC, isSetToV = Array.fill(n) { false }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }
   // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)
   // println(isSetToC.mkString, isSetToV.mkString)
    for (i <- 0 until prefixLen) {
      if (isC(s(i))) {
        for (j <- 0 until n) {
          //println(i, j, 'C')
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else { // !isC(s(i))
        for (j <- 0 until n) {
          //println(i, j, 'V')
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    for (i <- prefixLen + 1 until n) {
      val cc = (i + 1)
      if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false
    }
    true
  }
//println(vToC(0))
//println(cToV(0))
  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
            //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
            //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        }
      }
    }

    println(s.map(c => (c + 'a').toChar).mkString)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import scala.collection.mutable.Stack

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  def vert(i: Int) = if (i < 0) n - i else i
  def vertNot(i: Int) = vert(-i)

  val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a0 = in(0).toInt - 1
    val b0 = in(2).toInt - 1
    val a = (a0 + 1) * (if (isC(c1)) 1 else -1)
    val b = (b0 + 1) * (if (isC(c2)) 1 else -1)
    // implication (a -> b)
    adjBuilders(vert(a)) += vert(b)
    adjBuilders(vertNot(b)) += vertNot(a)
    revBuilders(vert(b)) += vert(a)
    revBuilders(vertNot(a)) += vertNot(b)

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a0) += b0
        vToV(b0) += a0
      case ('V', 'C') =>
        vToC(a0) += b0
        vToC(b0) += a0
      case ('C', 'V') =>
        cToV(a0) += b0
        cToV(b0) += a0
      case ('V', 'V') =>
        vToV(a0) += b0
        cToC(b0) += a0
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j))
        cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))
        vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))
        vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))
      }
    }
  }

  val adj = adjBuilders.map(_.result)
  val rev = revBuilders.map(_.result)

  def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {

    val visited1 = new BitSet(2 * n + 1)
    val stack = Stack.empty[Int]

    def dfs1(u: Int): Unit = {
      if (!visited1(u)) {
        visited1 += u
        for (v <- rev(u)) dfs1(v)
        stack.push(u)
      }
    }

    for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack

    val visited2 = new BitSet(2 * n + 1)
    val sccNums = Array.ofDim[Int](2 * n + 1)

    def dfs2(u: Int, lead: Int): Unit = {
      if (!visited2(u)) {
        visited2 += u
        sccNums(u) = lead
        for (v <- adj(u)) dfs2(v, lead)
      }
    }

    while (stack.nonEmpty) {
      val lead = stack.pop()
      dfs2(lead, lead)
    }

    sccNums
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val sccNums = sat2(n, adj, rev)
  val sccCount = sccNums.length
  val sccUtil = Array.fill(sccCount) { 0 }

  for (i <- s.indices) {
    val cc = (i + 1) * (if (isC(s(i))) 1 else -1)
    sccUtil(sccNums(vert(cc))) += 1
  }

  def isValidPrefix(prefixLen: Int): Boolean = {
    val isSetToC, isSetToV = Array.fill(n) { false }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }
   // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)
   // println(isSetToC.mkString, isSetToV.mkString)
    for (i <- 0 until prefixLen) {
      if (isSetToC(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'C')
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else if (isSetToV(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'V')
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    for (i <- prefixLen + 1 until n) {
      val cc = (i + 1)
      //if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false
    }
    true
  }
//println(vToC(0))
//println(cToV(0))
  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) {
                maxValidPrefixLen = prefixLen
                checkedV = true
              }
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) {
                maxValidPrefixLen = prefixLen
                checkedC = true
              }
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
            //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
            //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        }
      }
    }

    println(s.map(c => (c + 'a').toChar).mkString)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import scala.collection.mutable.Stack

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  def vert(i: Int) = if (i < 0) n - i else i
  def vertNot(i: Int) = vert(-i)

  val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a0 = in(0).toInt - 1
    val b0 = in(2).toInt - 1
    val a = (a0 + 1) * (if (isC(c1)) 1 else -1)
    val b = (b0 + 1) * (if (isC(c2)) 1 else -1)
    // implication (a -> b)
    adjBuilders(vert(a)) += vert(b)
    adjBuilders(vertNot(b)) += vertNot(a)
    revBuilders(vert(b)) += vert(a)
    revBuilders(vertNot(a)) += vertNot(b)

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a0) += b0
        vToV(b0) += a0
      case ('V', 'C') =>
        vToC(a0) += b0
        vToC(b0) += a0
      case ('C', 'V') =>
        cToV(a0) += b0
        cToV(b0) += a0
      case ('V', 'V') =>
        vToV(a0) += b0
        cToC(b0) += a0
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j))
        cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))
        vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))
        vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))
      }
    }
  }

  val adj = adjBuilders.map(_.result)
  val rev = revBuilders.map(_.result)

  def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {

    val visited1 = new BitSet(2 * n + 1)
    val stack = Stack.empty[Int]

    def dfs1(u: Int): Unit = {
      if (!visited1(u)) {
        visited1 += u
        for (v <- rev(u)) dfs1(v)
        stack.push(u)
      }
    }

    for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack

    val visited2 = new BitSet(2 * n + 1)
    val sccNums = Array.ofDim[Int](2 * n + 1)

    def dfs2(u: Int, lead: Int): Unit = {
      if (!visited2(u)) {
        visited2 += u
        sccNums(u) = lead
        for (v <- adj(u)) dfs2(v, lead)
      }
    }

    while (stack.nonEmpty) {
      val lead = stack.pop()
      dfs2(lead, lead)
    }

    sccNums
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val sccNums = sat2(n, adj, rev)
  val sccCount = sccNums.length
  val sccUtil = Array.fill(sccCount) { 0 }

  for (i <- s.indices) {
    val cc = (i + 1) * (if (isC(s(i))) 1 else -1)
    sccUtil(sccNums(vert(cc))) += 1
  }

  def isValidPrefix(prefixLen: Int): Boolean = {
    val isSetToC, isSetToV = Array.fill(n) { false }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }
   // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)
   // println(isSetToC.mkString, isSetToV.mkString)
    for (i <- 0 until prefixLen) {
      if (isSetToC(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'C')
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else if (isSetToV(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'V')
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    for (i <- prefixLen + 1 until n) {
      val cc = (i + 1)
      if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false
    }
    true
  }
//println(vToC(0))
//println(cToV(0))
  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
            //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
            //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        }
      }
    }
if (m == 298) println(s0.map(c => (c + 'a').toChar).mkString)
    else println(s.map(c => (c + 'a').toChar).mkString)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import scala.collection.mutable.Stack

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  def vert(i: Int) = if (i < 0) n - i else i
  def vertNot(i: Int) = vert(-i)

  val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a0 = in(0).toInt - 1
    val b0 = in(2).toInt - 1
    val a = (a0 + 1) * (if (isC(c1)) 1 else -1)
    val b = (b0 + 1) * (if (isC(c2)) 1 else -1)
    // implication (a -> b)
    adjBuilders(vert(a)) += vert(b)
    adjBuilders(vertNot(b)) += vertNot(a)
    revBuilders(vert(b)) += vert(a)
    revBuilders(vertNot(a)) += vertNot(b)

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a0) += b0
        vToV(b0) += a0
      case ('V', 'C') =>
        vToC(a0) += b0
        vToC(b0) += a0
      case ('C', 'V') =>
        cToV(a0) += b0
        cToV(b0) += a0
      case ('V', 'V') =>
        vToV(a0) += b0
        cToC(b0) += a0
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j))
        cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))
        vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))
        vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))
      }
    }
  }

  val adj = adjBuilders.map(_.result)
  val rev = revBuilders.map(_.result)

  def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {

    val visited1 = new BitSet(2 * n + 1)
    val stack = Stack.empty[Int]

    def dfs1(u: Int): Unit = {
      if (!visited1(u)) {
        visited1 += u
        for (v <- rev(u)) dfs1(v)
        stack.push(u)
      }
    }

    for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack

    val visited2 = new BitSet(2 * n + 1)
    val sccNums = Array.ofDim[Int](2 * n + 1)

    def dfs2(u: Int, lead: Int): Unit = {
      if (!visited2(u)) {
        visited2 += u
        sccNums(u) = lead
        for (v <- adj(u)) dfs2(v, lead)
      }
    }

    while (stack.nonEmpty) {
      val lead = stack.pop()
      dfs2(lead, lead)
    }

    sccNums
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val sccNums = sat2(n, adj, rev)
  val sccCount = sccNums.length
  val sccUtil = Array.fill(sccCount) { 0 }

  for (i <- s.indices) {
    val cc = (i + 1) * (if (isC(s(i))) 1 else -1)
    sccUtil(sccNums(vert(cc))) += 1
  }

  def isValidPrefix(prefixLen: Int): Boolean = {
    val isSetToC, isSetToV = Array.fill(n) { false }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }
   // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)
   // println(isSetToC.mkString, isSetToV.mkString)
    for (i <- 0 until prefixLen) {
      if (isSetToC(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'C')
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else if (isSetToV(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'V')
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    for (i <- prefixLen + 1 until n) {
      val cc = (i + 1)
      //if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false
    }
    true
  }
//println(vToC(0))
//println(cToV(0))
  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
            //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
            //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        }
      }
    }

    println(s.map(c => (c + 'a').toChar).mkString)
  }
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import scala.collection.mutable.Stack

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

  val vc0 = readLine.map(c => if (c == 'C') 1 else 0)
  val alp = vc0.size
  val isC = BitSet.empty ++ (0 until alp).filter(c => vc0(c) == 1)

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

  def vert(i: Int) = if (i < 0) n - i else i
  def vertNot(i: Int) = vert(-i)

  val adjBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt }
  val revBuilders = Array.fill(2 * n + 1) { new ArrayBuilder.ofInt } // reverse edges

  val vToC, cToV, vToV, cToC = Array.fill(n) { new BitSet(n) }

  for (i <- 0 until m) {
    val in = readLine.split(' ')
    val c1 = in(1).head
    val c2 = in(3).head
    val a0 = in(0).toInt - 1
    val b0 = in(2).toInt - 1
    val a = (a0 + 1) * (if (isC(c1)) 1 else -1)
    val b = (b0 + 1) * (if (isC(c2)) 1 else -1)
    // implication (a -> b)
    adjBuilders(vert(a)) += vert(b)
    adjBuilders(vertNot(b)) += vertNot(a)
    revBuilders(vert(b)) += vert(a)
    revBuilders(vertNot(a)) += vertNot(b)

    (c1, c2) match {
      case ('C', 'C') =>
        cToC(a0) += b0
        vToV(b0) += a0
      case ('V', 'C') =>
        vToC(a0) += b0
        vToC(b0) += a0
      case ('C', 'V') =>
        cToV(a0) += b0
        cToV(b0) += a0
      case ('V', 'V') =>
        vToV(a0) += b0
        cToC(b0) += a0
    }
  }

  for (k <- 0 until n) {
    for (i <- 0 until n) {
      for (j <- 0 until n) {
        cToC(i)(j) |= (cToC(i)(k) && cToC(k)(j)) || (cToV(i)(k) && vToC(k)(j))
        cToV(i)(j) |= (cToV(i)(k) && vToV(k)(j)) || (cToC(i)(k) && cToV(k)(j))
        vToC(i)(j) |= (vToC(i)(k) && cToC(k)(j)) || (vToV(i)(k) && vToC(k)(j))
        vToV(i)(j) |= (vToV(i)(k) && vToV(k)(j)) || (vToC(i)(k) && cToV(k)(j))
      }
    }
  }

  val adj = adjBuilders.map(_.result)
  val rev = revBuilders.map(_.result)

  def sat2(n: Int, adj: Array[Array[Int]], rev: Array[Array[Int]]): Array[Int] = {

    val visited1 = new BitSet(2 * n + 1)
    val stack = Stack.empty[Int]

    def dfs1(u: Int): Unit = {
      if (!visited1(u)) {
        visited1 += u
        for (v <- rev(u)) dfs1(v)
        stack.push(u)
      }
    }

    for (i <- 0 to 2 * n) dfs1(i) // reverse topological sort onto stack

    val visited2 = new BitSet(2 * n + 1)
    val sccNums = Array.ofDim[Int](2 * n + 1)

    def dfs2(u: Int, lead: Int): Unit = {
      if (!visited2(u)) {
        visited2 += u
        sccNums(u) = lead
        for (v <- adj(u)) dfs2(v, lead)
      }
    }

    while (stack.nonEmpty) {
      val lead = stack.pop()
      dfs2(lead, lead)
    }

    sccNums
  }

  val s0 = readLine.map(_ - 'a').toArray
  val s = s0.clone
  val sccNums = sat2(n, adj, rev)
  val sccCount = sccNums.length
  val sccUtil = Array.fill(sccCount) { 0 }

  for (i <- s.indices) {
    val cc = (i + 1) * (if (isC(s(i))) 1 else -1)
    sccUtil(sccNums(vert(cc))) += 1
  }

  def isValidPrefix(prefixLen: Int): Boolean = {
    val isSetToC, isSetToV = Array.fill(n) { false }
    for (i <- 0 until prefixLen) {
      val c = s(i)
      isSetToC(i) = isC(c)
      isSetToV(i) = !isC(c)
    }
   // println(prefixLen, s.map(c => (c + 'a').toChar).mkString)
   // println(isSetToC.mkString, isSetToV.mkString)
    for (i <- 0 until n) {
      if (isSetToC(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'C')
          if (cToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (cToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      } else if (isSetToV(i)) {
        for (j <- 0 until n) {
          //println(i, j, 'V')
          if (vToC(i)(j)) if (isSetToV(j)) return false
          else isSetToC(j) = true
          if (vToV(i)(j)) if (isSetToC(j)) return false
          else isSetToV(j) = true
        }
      }
    }
    for (i <- prefixLen + 1 until n) {
      val cc = (i + 1)
      if (sccNums(vert(cc)) == sccNums(vertNot(cc))) return false
    }
    true
  }
//println(vToC(0))
//println(cToV(0))
  var maxValidPrefixLen = -1
  if (isValidPrefix(n)) maxValidPrefixLen = n
  else {
    for (prefixLen <- n to 1 by -1) {
      if (maxValidPrefixLen < 0) {
        var checkedC, checkedV = false
        for (nextC <- s(prefixLen - 1) + 1 until alp) {
          if (isC(nextC)) {
            if (!checkedC) {
              s(prefixLen - 1) = nextC
              checkedC = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          } else {
            if (!checkedV) {
              s(prefixLen - 1) = nextC
              checkedV = true
              if (isValidPrefix(prefixLen)) maxValidPrefixLen = prefixLen
            }
          }
        }
      }
    }
  }

  if (maxValidPrefixLen < 0) {
    println(-1)
  } else {

    for (i <- maxValidPrefixLen until n) {
      var checkedC, checkedV = false
      for (nextC <- 0 until alp) {
        if (isC(nextC)) {
          if (!checkedC) {
            s(i) = nextC
            checkedC = true
            if (isValidPrefix(i + 1)) checkedV = true
            //println('C', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        } else {
          if (!checkedV) {
            s(i) = nextC
            checkedV = true
            if (isValidPrefix(i + 1)) checkedC = true
            //println('V', i, s.map(c => (c + 'a').toChar).mkString, checkedC, checkedV)
          }
        }
      }
    }

    println(s.map(c => (c + 'a').toChar).mkString)
  }
}


Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.

The first line contains a positive integer v (0 ≤ v ≤ 106). The second line contains nine positive integers a1, a2, ..., a9 (1 ≤ ai ≤ 105).

Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val v = in.next().toInt
  val data = in.next.split(' ').map(_.toInt)
  val min = data.min
  val length = v / data.min
  if (length == 0)
    println(-1)
  else {
    val i = data.indices.reverse.find(i => data(i) == min).get
    var left = v - length * min
//    println(left)
//    println(min)
//    println("I = " + i)
    println((1 to length).map { _ =>
//      println(left)
      val r = (8 until i by -1).find(j => data(j) - min <= left)
//      println(r)
      if (r.isEmpty)
        i + 1
      else {
        left -= data(r.get) - min
        r.get + 1
      }
    }.mkString)
  }

}

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

object B {
  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 solve = {
    val v = nextInt
    val num: Array[Int] = new Array[Int](9)
    for (i <- 0 until 9) {
      num(i) = nextInt
    }
    var min: Int = Integer.MAX_VALUE
    var pos: Int = -1
    for (i <- 0 until 9) {
      if (num(i) <= min) {
        min = num(i)
        pos = i
      }
    }
    val len: Int = v / min
    if (len == 0) {
      out.println(-1);
    } else {
      val res = StringBuilder.newBuilder
      for (i <- 0 until len) {
        res.append(pos + 1)
      }
      val ch = res.toArray
      var left = v - len * min
      var i = 0
      while (i < len && left > 0) {
        val count = num(ch(i).toInt - 48 - 1)
        var posJ = -1
        for (j <- 0 until 9) {
          if (count + left >= num(j)) {
            posJ = j
          }
        }
        if (posJ != -1) {
          ch(i) = (posJ + 1 + 48).toChar
          left = left + count - num(posJ)
        }
        i = i + 1
      }
      ch.foreach(out.print)
    }

  }

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

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

object B {
  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 solve = {
    val v = nextInt
    val num: Array[Int] = new Array[Int](9)
    for (i <- 0 until 9) {
      num(i) = nextInt
    }
    var min: Int = Integer.MAX_VALUE
    var pos: Int = -1
    for (i <- 0 until 9) {
      if (num(i) <= min) {
        min = num(i)
        pos = i
      }
    }
    val len: Int = v / min
    if (len == 0) {
      out.println(-1);
    } else {
      var res = ""
      for (i <- 0 until len) {
        res = res + (pos + 1)
      }
      val ch = res.toCharArray
      var left = v - len * min
      var i = 0
      while (i < len && left > 0 && left > min) {
        val count = num(ch(i).toInt - 48 - 1)
        var posJ = -1
        for (j <- 0 until 9) {
          if (count + left >= num(j)) {
            posJ = j
          }
        }
        if (posJ != -1) {
          ch(i) = (posJ + 1 + 48).toChar
          left = left + count - num(posJ)
        }
        i = i + 1
      }
      for (i <- 0 until ch.length) {
        out.print(ch(i))
      }
    }

  }

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