The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.Nam created a sequence a consisting of n (1 ≤ n ≤ 105) elements a1, a2, ..., an (1 ≤ ai ≤ 105). A subsequence ai1, ai2, ..., aik where 1 ≤ i1 < i2 < ... < ik ≤ n is called increasing if ai1 < ai2 < ai3 < ... < aik. An increasing subsequence is called longest if it has maximum length among all increasing subsequences. Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes i (1 ≤ i ≤ n), into three groups: group of all i such that ai belongs to no longest increasing subsequences. group of all i such that ai belongs to at least one but not every longest increasing subsequence. group of all i such that ai belongs to every longest increasing subsequence. Since the number of longest increasing subsequences of a may be very large, categorizing process is very difficult. Your task is to help him finish this job.

The first line contains the single integer n (1 ≤ n ≤ 105) denoting the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105).

Print a string consisting of n characters. i-th character should be '1', '2' or '3' depending on which group among listed above index i belongs to.

NoteIn the second sample, sequence a consists of 4 elements: {a1, a2, a3, a4} = {1, 3, 2, 5}. Sequence a has exactly 2 longest increasing subsequences of length 3, they are {a1, a2, a4} = {1, 3, 5} and {a1, a3, a4} = {1, 2, 5}.In the third sample, sequence a consists of 4 elements: {a1, a2, a3, a4} = {1, 5, 2, 3}. Sequence a have exactly 1 longest increasing subsequence of length 3, that is {a1, a3, a4} = {1, 2, 3}.

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

object Solution {
    val MOD = 1000 * 1000 * 1000 + 9
    val N = 100 * 1000 + 10

    class SegmentTree(val n : Int) {
        private val data = new Array[Int](4 * n + 10)
        private val ways = new Array[Int](4 * n + 10)
        Arrays.fill(ways, 1)

        def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)

        private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {
            if (l == tl && r == tr)
                return (data(i), ways(i))
            var sl = 0
            var sr = 0
            var wl = 1
            var wr = 1
            val m = (tl + tr) / 2
            if (l <= m) {
                val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))
                sl = t._1
                wl = t._2
            }
            if (r > m) {
                val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)
                sr = t._1
                wr = t._2
            }
            if (sl == sr && sl != 0)
                (sl, (wl + wr) % MOD)
            else if (sl > sr)
                (sl, wl)
            else
                (sr, wr)
        }

        def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)

        private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {
            if (pos == tl && pos == tr) {
                if (data(i) == value)
                    ways(i) = (ways(i) + add) % MOD
                else if (data(i) < value) {
                    data(i) = value
                    ways(i) = add
                }
                return
            }
            val m = (tl + tr) / 2
            if (pos <= m)
                put(2 * i + 1, tl, m, pos, value, add)
            else
                put(2 * i + 2, m + 1, tr, pos, value, add)
            if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {
                data(i) = data(2 * i + 1)
                ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD
            } else if (data(2 * i + 1) > data(2 * i + 2)) {
                data(i) = data(2 * i + 1)
                ways(i) = ways(2 * i + 1)
            } else {
                data(i) = data(2 * i + 2)
                ways(i) = ways(2 * i + 2)
            }
        }
    }

    def solve(in: FastScanner, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = new Array[Int](n)
        var i = 0
        for (i <- 0 until n)
            a(i) = in.nextInt()
        val equalLeft = new Array[Int](n)
        val equalRight = new Array[Int](n)
        val lessLeft = new Array[Int](n)
        val greaterRight = new Array[Int](n)
        val cntLess = new Array[Int](n)
        val treeLeft = new SegmentTree(N)
        for (i <- 0 until n) {
            equalLeft(i) = treeLeft.getMax(0, a(i))._1
            lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1
            cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2
            treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))
        }
        val maxSeq = treeLeft.getMax(0, N - 1)
        val maxLen = maxSeq._1
        val cntTotal = maxSeq._2
        val treeRight = new SegmentTree(N)
        val res = new Array[Int](n)
        for (i <- 0 until n) {
            val j = n - i - 1
            equalRight(j) = treeRight.getMax(a(j), N - 1)._1
            greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1
            val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2
            treeRight.put(a(j), greaterRight(j) + 1, cntGreater)
            val any = lessLeft(j) + greaterRight(j) + 1 == maxLen
            if (!any) {
                res(j) = 1
            } else {
                if (cntLess(j) * 1L * cntGreater % MOD == cntTotal)
                    res(j) = 3
                else
                    res(j) = 2
            }
        }
        for (i <- 0 until n)
            out.print(res(i))
        out.println()
    }

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

    class FastScanner(val in: InputStream) {
        var st: StringTokenizer = null
        var br = new BufferedReader(new InputStreamReader(in))

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

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

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

        def close(): Unit = {
            br.close()
        }
    }
}

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

object Solution {
    val MOD = 1000 * 1000 * 1000 + 9
    val N = 100 * 1000 + 10

    class SegmentTree(val n : Int) {
        private val data = new Array[Int](4 * n + 10)
        private val ways = new Array[Int](4 * n + 10)
        Arrays.fill(ways, 1)

        def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)

        private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {
            if (l == tl && r == tr)
                return (data(i), ways(i))
            var sl = 0
            var sr = 0
            var wl = 1
            var wr = 1
            val m = (tl + tr) / 2
            if (l <= m) {
                val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))
                sl = t._1
                wl = t._2
            }
            if (r > m) {
                val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)
                sr = t._1
                wr = t._2
            }
            if (sl == sr && sl != 0)
                (sl, (wl + wr) % MOD)
            else if (sl > sr)
                (sl, wl)
            else
                (sr, wr)
        }

        def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)

        private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {
            if (pos == tl && pos == tr) {
                if (data(i) == value)
                    ways(i) = (ways(i) + add) % MOD
                else if (data(i) < value) {
                    data(i) = value
                    ways(i) = add
                }
                return
            }
            val m = (tl + tr) / 2
            if (pos <= m)
                put(2 * i + 1, tl, m, pos, value, add)
            else
                put(2 * i + 2, m + 1, tr, pos, value, add)
            if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {
                data(i) = data(2 * i + 1)
                ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD
            } else if (data(2 * i + 1) > data(2 * i + 2)) {
                data(i) = data(2 * i + 1)
                ways(i) = ways(2 * i + 1)
            } else {
                data(i) = data(2 * i + 2)
                ways(i) = ways(2 * i + 2)
            }
        }
    }

    def solve(in: FastScanner, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = new Array[Int](n)
        var i = 0
        for (i <- 0 until n)
            a(i) = in.nextInt()
        val equalLeft = new Array[Int](n)
        val equalRight = new Array[Int](n)
        val lessLeft = new Array[Int](n)
        val greaterRight = new Array[Int](n)
        val cntLess = new Array[Int](n)
        val treeLeft = new SegmentTree(N)
        for (i <- 0 until n) {
            equalLeft(i) = treeLeft.getMax(0, a(i))._1
            lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1
            cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2
            treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))
        }
        val maxSeq = treeLeft.getMax(0, N - 1)
        val maxLen = maxSeq._1
        val cntTotal = maxSeq._2
        val treeRight = new SegmentTree(N)
        val res = new Array[Int](n)
        for (i <- 0 until n) {
            val j = n - i - 1
            equalRight(j) = treeRight.getMax(a(j), N - 1)._1
            greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1
            val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2
            treeRight.put(a(j), greaterRight(j) + 1, cntGreater)
            val any = lessLeft(j) + greaterRight(j) + 1 == maxLen
            if (!any) {
                res(j) = 1
            } else {
                if (cntLess(j) * 1L * cntGreater == cntTotal)
                    res(j) = 3
                else
                    res(j) = 2
            }
        }
        for (i <- 0 until n)
            out.print(res(i))
        out.println()
    }

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

    class FastScanner(val in: InputStream) {
        var st: StringTokenizer = null
        var br = new BufferedReader(new InputStreamReader(in))

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

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

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

        def close(): Unit = {
            br.close()
        }
    }
}

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

object Solution {
    val MOD = 1000 * 1000 * 1000 + 7
    val N = 100 * 1000 + 10

    class SegmentTree(val n : Int) {
        private val data = new Array[Int](4 * n + 10)
        private val ways = new Array[Int](4 * n + 10)
        Arrays.fill(ways, 1)

        def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)

        private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {
            if (l == tl && r == tr)
                return (data(i), ways(i))
            var sl = 0
            var sr = 0
            var wl = 1
            var wr = 1
            val m = (tl + tr) / 2
            if (l <= m) {
                val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))
                sl = t._1
                wl = t._2
            }
            if (r > m) {
                val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)
                sr = t._1
                wr = t._2
            }
            if (sl == sr && sl != 0)
                (sl, wl + wr)
            else if (sl > sr)
                (sl, wl)
            else
                (sr, wr)
        }

        def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)

        private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {
            if (pos == tl && pos == tr) {
                if (data(i) == value)
                    ways(i) = (ways(i) + add) % MOD
                else if (data(i) < value) {
                    data(i) = value
                    ways(i) = add
                }
                return
            }
            val m = (tl + tr) / 2
            if (pos <= m)
                put(2 * i + 1, tl, m, pos, value, add)
            else
                put(2 * i + 2, m + 1, tr, pos, value, add)
            if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {
                data(i) = data(2 * i + 1)
                ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD
            } else if (data(2 * i + 1) > data(2 * i + 2)) {
                data(i) = data(2 * i + 1)
                ways(i) = ways(2 * i + 1)
            } else {
                data(i) = data(2 * i + 2)
                ways(i) = ways(2 * i + 2)
            }
        }
    }

    def solve(in: FastScanner, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = new Array[Int](n)
        var i = 0
        for (i <- 0 until n)
            a(i) = in.nextInt()
        val equalLeft = new Array[Int](n)
        val equalRight = new Array[Int](n)
        val lessLeft = new Array[Int](n)
        val greaterRight = new Array[Int](n)
        val cntLess = new Array[Int](n)
        val treeLeft = new SegmentTree(N)
        for (i <- 0 until n) {
            equalLeft(i) = treeLeft.getMax(0, a(i))._1
            lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1
            cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2
            treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))
        }
        val maxSeq = treeLeft.getMax(0, N - 1)
        val maxLen = maxSeq._1
        val cntTotal = maxSeq._2
        //System.err.print(maxLen + " " + cntTotal)
        val treeRight = new SegmentTree(N)
        for (i <- 0 until n) {
            val j = n - i - 1
            equalRight(j) = treeRight.getMax(a(j), N - 1)._1
            greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1
            val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2
            treeRight.put(a(j), greaterRight(j) + 1, cntGreater)
            //System.err.println(cntLess(j) + " " + cntGreater)
            //System.err.println(lessLeft(j) + " " + equalLeft(j) + " " + equalRight(j) + " " + greaterRight(j))
            val any = lessLeft(j) + greaterRight(j) + 1 == maxLen
            if (!any) {
                out.print(1)
            } else {
                if (cntLess(j) * 1L * cntGreater == cntTotal)
                    out.print(3)
                else
                    out.print(2)
            }
        }
        out.println()
    }

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

    class FastScanner(val in: InputStream) {
        var st: StringTokenizer = null
        var br = new BufferedReader(new InputStreamReader(in))

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

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

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

        def close(): Unit = {
            br.close()
        }
    }
}

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

object Solution {
    val MOD = 1000 * 1000 * 1000 + 7
    val N = 100 * 1000 + 10

    class SegmentTree(val n : Int) {
        private val data = new Array[Int](4 * n + 10)
        private val ways = new Array[Int](4 * n + 10)
        Arrays.fill(ways, 1)

        def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)

        private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {
            if (l == tl && r == tr)
                return (data(i), ways(i))
            var sl = 0
            var sr = 0
            var wl = 1
            var wr = 1
            val m = (tl + tr) / 2
            if (l <= m) {
                val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))
                sl = t._1
                wl = t._2
            }
            if (r > m) {
                val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)
                sr = t._1
                wr = t._2
            }
            if (sl == sr && sl != 0)
                (sl, wl + wr)
            else if (sl > sr)
                (sl, wl)
            else
                (sr, wr)
        }

        def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)

        private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {
            if (pos == tl && pos == tr) {
                if (data(i) == value)
                    ways(i) = (ways(i) + add) % MOD
                else if (data(i) < value) {
                    data(i) = value
                    ways(i) = add
                }
                return
            }
            val m = (tl + tr) / 2
            if (pos <= m)
                put(2 * i + 1, tl, m, pos, value, add)
            else
                put(2 * i + 2, m + 1, tr, pos, value, add)
            if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {
                data(i) = data(2 * i + 1)
                ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD
            } else if (data(2 * i + 1) > data(2 * i + 2)) {
                data(i) = data(2 * i + 1)
                ways(i) = ways(2 * i + 1)
            } else {
                data(i) = data(2 * i + 2)
                ways(i) = ways(2 * i + 2)
            }
        }
    }

    def solve(in: FastScanner, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = new Array[Int](n)
        var i = 0
        for (i <- 0 until n)
            a(i) = in.nextInt()
        val equalLeft = new Array[Int](n)
        val equalRight = new Array[Int](n)
        val lessLeft = new Array[Int](n)
        val greaterRight = new Array[Int](n)
        val cntLess = new Array[Int](n)
        val treeLeft = new SegmentTree(N)
        for (i <- 0 until n) {
            equalLeft(i) = treeLeft.getMax(0, a(i))._1
            lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1
            cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2
            treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))
        }
        val maxSeq = treeLeft.getMax(0, N - 1)
        val maxLen = maxSeq._1
        val cntTotal = maxSeq._2
        //System.err.print(maxLen + " " + cntTotal)
        val treeRight = new SegmentTree(N)
        val res = new Array[Int](n)
        for (i <- 0 until n) {
            val j = n - i - 1
            equalRight(j) = treeRight.getMax(a(j), N - 1)._1
            greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1
            val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2
            treeRight.put(a(j), greaterRight(j) + 1, cntGreater)
            //System.err.println(cntLess(j) + " " + cntGreater)
            //System.err.println(lessLeft(j) + " " + equalLeft(j) + " " + equalRight(j) + " " + greaterRight(j))
            val any = lessLeft(j) + greaterRight(j) + 1 == maxLen
            if (!any) {
                res(j) = 1
            } else {
                if (cntLess(j) * 1L * cntGreater == cntTotal)
                    res(j) = 3
                else
                    res(j) = 2
            }
        }
        for (i <- 0 until n)
            out.print(res(i))
        out.println()
    }

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

    class FastScanner(val in: InputStream) {
        var st: StringTokenizer = null
        var br = new BufferedReader(new InputStreamReader(in))

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

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

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

        def close(): Unit = {
            br.close()
        }
    }
}

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

object Solution {
    val MOD = 1000 * 1000 * 1000 + 7
    val N = 100 * 1000 + 10

    class SegmentTree(val n : Int) {
        private val data = new Array[Int](4 * n + 10)
        private val ways = new Array[Int](4 * n + 10)
        Arrays.fill(ways, 1)

        def getMax(l: Int, r : Int): (Int, Int) = getMax(0, 0, n - 1, l, r)

        private def getMax(i: Int, tl: Int, tr: Int, l: Int, r: Int): (Int, Int) = {
            if (l == tl && r == tr)
                return (data(i), ways(i))
            var sl = 0
            var sr = 0
            var wl = 1
            var wr = 1
            val m = (tl + tr) / 2
            if (l <= m) {
                val t = getMax(2 * i + 1, tl, m, l, Math.min(r, m))
                sl = t._1
                wl = t._2
            }
            if (r > m) {
                val t = getMax(2 * i + 2, m + 1, tr, Math.max(m + 1, l), r)
                sr = t._1
                wr = t._2
            }
            if (sl == sr && sl != 0)
                (sl, (wl + wr) % MOD)
            else if (sl > sr)
                (sl, wl)
            else
                (sr, wr)
        }

        def put(pos: Int, value: Int, add: Int): Unit = put(0, 0, n - 1, pos, value, add)

        private def put(i: Int, tl: Int, tr: Int, pos: Int, value: Int, add: Int): Unit = {
            if (pos == tl && pos == tr) {
                if (data(i) == value)
                    ways(i) = (ways(i) + add) % MOD
                else if (data(i) < value) {
                    data(i) = value
                    ways(i) = add
                }
                return
            }
            val m = (tl + tr) / 2
            if (pos <= m)
                put(2 * i + 1, tl, m, pos, value, add)
            else
                put(2 * i + 2, m + 1, tr, pos, value, add)
            if (data(2 * i + 1) == data(2 * i + 2) && data(2 * i + 1) != 0) {
                data(i) = data(2 * i + 1)
                ways(i) = (ways(2 * i + 1) + ways(2 * i + 2)) % MOD
            } else if (data(2 * i + 1) > data(2 * i + 2)) {
                data(i) = data(2 * i + 1)
                ways(i) = ways(2 * i + 1)
            } else {
                data(i) = data(2 * i + 2)
                ways(i) = ways(2 * i + 2)
            }
        }
    }

    def solve(in: FastScanner, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val a = new Array[Int](n)
        var i = 0
        for (i <- 0 until n)
            a(i) = in.nextInt()
        val equalLeft = new Array[Int](n)
        val equalRight = new Array[Int](n)
        val lessLeft = new Array[Int](n)
        val greaterRight = new Array[Int](n)
        val cntLess = new Array[Int](n)
        val treeLeft = new SegmentTree(N)
        for (i <- 0 until n) {
            equalLeft(i) = treeLeft.getMax(0, a(i))._1
            lessLeft(i) = treeLeft.getMax(0, a(i) - 1)._1
            cntLess(i) = treeLeft.getMax(0, a(i) - 1)._2
            treeLeft.put(a(i), lessLeft(i) + 1, cntLess(i))
        }
        val maxSeq = treeLeft.getMax(0, N - 1)
        val maxLen = maxSeq._1
        val cntTotal = maxSeq._2
        val treeRight = new SegmentTree(N)
        val res = new Array[Int](n)
        for (i <- 0 until n) {
            val j = n - i - 1
            equalRight(j) = treeRight.getMax(a(j), N - 1)._1
            greaterRight(j) = treeRight.getMax(a(j) + 1, N - 1)._1
            val cntGreater = treeRight.getMax(a(j) + 1, N - 1)._2
            treeRight.put(a(j), greaterRight(j) + 1, cntGreater)
            val any = lessLeft(j) + greaterRight(j) + 1 == maxLen
            if (!any) {
                res(j) = 1
            } else {
                if (cntLess(j) * 1L * cntGreater == cntTotal)
                    res(j) = 3
                else
                    res(j) = 2
            }
        }
        for (i <- 0 until n)
            out.print(res(i))
        out.println()
    }

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

    class FastScanner(val in: InputStream) {
        var st: StringTokenizer = null
        var br = new BufferedReader(new InputStreamReader(in))

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

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

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

        def close(): Unit = {
            br.close()
        }
    }
}


Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w":   "vvvv"  "vvvv"  "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows:  "vvvovvv"  "vvvovvv"  "vvvovvv"  "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov".

The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$.

Output a single integer, the wow factor of $$$s$$$.

NoteThe first example is explained in the legend.

object B extends App {

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

  val s = readLine

  var res = 0L
  var w = 0L
  var wo = 0L

  for (i <- 1 until s.length) {
    if (s(i) == 'v' && s(i - 1) == 'v') {
      res += wo
      w += 1
    } else if (s(i) == 'o') {
      wo += w
    }
  }

  println(res)
}

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

  override def apply(io: IO): io.type = {
    val s = io.read[String]
      .replace("ovo", "oo")
      .replace("ov", "o,v")
      .replace("vo", "v,o")
      .split(",")
      .view
      .map(t => if (t.startsWith("v")) ('w', t.length - 1) else ('o', t.length))

    @tailrec
    def solve(i: Int, wc: Long, owc: Long, wowc: Long): Long = {
      if (i < 0) {
        wowc
      } else {
        s(i) match {
          case ('w', w) => solve(i - 1, wc = wc + w, owc = owc       , wowc = wowc + w*owc)
          case ('o', o) => solve(i - 1, wc = wc    , owc = owc + o*wc, wowc = wowc)
          case _ => throw new IllegalStateException()
        }
      }
    }

    val ans = solve(i = s.length - 1, wc = 0, owc = 0, wowc = 0)
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

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


You have a long fence which consists of $$$n$$$ sections. Unfortunately, it is not painted, so you decided to hire $$$q$$$ painters to paint it. $$$i$$$-th painter will paint all sections $$$x$$$ such that $$$l_i \le x \le r_i$$$.Unfortunately, you are on a tight budget, so you may hire only $$$q - 2$$$ painters. Obviously, only painters you hire will do their work.You want to maximize the number of painted sections if you choose $$$q - 2$$$ painters optimally. A section is considered painted if at least one painter paints it.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$3 \le n, q \le 5000$$$) — the number of sections and the number of painters availible for hire, respectively. Then $$$q$$$ lines follow, each describing one of the painters: $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).

Print one integer — maximum number of painted sections if you hire $$$q - 2$$$ painters.

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, Q = ni()
    val (l, r) = na2(Q, -1)

    var ans = 0

    val cum = Array.ofDim[Int](N + 2)
    val cumOne = Array.ofDim[Int](N + 1)

    REP(Q) { del =>
      java.util.Arrays.fill(cum, 0)
      java.util.Arrays.fill(cumOne, 0)
      REP(Q) { i =>
        if (del != i) {
          cum(l(i) + 1) += 1
          cum(r(i) + 2) -= 1
        }
      }
      REP(N + 1) { i =>
        cum(i + 1) += cum(i)
      }

//      debug(cum)

      REP(N) { i =>
        cumOne(i + 1) = cumOne(i)
        if (cum(i + 1) == 1) cumOne(i + 1) += 1
      }

//      debug(cumOne)

      val S = cum.count(_ > 0)
      REP(Q) { i =>
        if (i != del) {
          val cnt = cumOne(r(i) + 1) - cumOne(l(i))
          val v = S - cnt
//          debug(s"del:($del,$i) $cnt $v")
          ans = max(ans, v)
        }
      }
    }

    out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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


You are given a grid, consisting of $$$2$$$ rows and $$$n$$$ columns. Each cell of this grid should be colored either black or white.Two cells are considered neighbours if they have a common border and share the same color. Two cells $$$A$$$ and $$$B$$$ belong to the same component if they are neighbours, or if there is a neighbour of $$$A$$$ that belongs to the same component with $$$B$$$.Let's call some bicoloring beautiful if it has exactly $$$k$$$ components.Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $$$998244353$$$.

The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1000$$$, $$$1 \le k \le 2n$$$) — the number of columns in a grid and the number of components required.

Print a single integer — the number of beautiful bicolorings modulo $$$998244353$$$.

NoteOne of possible bicolorings in sample $$$1$$$:

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    var cur, next = Array.ofDim[Long](4, 2001) // 0: BB, 1: BW, 2: WB, 3:WW
    cur(0)(1) = 1
    cur(1)(2) = 1
    cur(2)(2) = 1
    cur(3)(1) = 1

    rep(N - 1) { _ =>
      rep(4) { i =>
        rep(4) { j =>
          rep(2001) { k =>
            val pls =
              if (i == 1 || i == 2) {
                // BW
                // WB
                if (i == 1 && j == 2 || i == 2 && j == 1) 2
                // BB
                // WB
                else 0
              } else {
                // Ww
                // WB
                if (i != j) 1
                // Ww
                // WW
                else 0
              }

            if (k + pls <= 2000) next(j)(k + pls) = (next(j)(k + pls) + cur(i)(k)) % MOD
          }
        }
      }

      val t = cur
      cur = next
      next = t
      rep(4)(i => java.util.Arrays.fill(next(i), 0))
    }

    val ans = cur.map(_(K)).sum
    out.println(ans % MOD)
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    var cur, next = Array.ofDim[Long](4, 2001) // 0: BB, 1: BW, 2: WB, 3:WW
    cur(0)(1) = 1
    cur(1)(2) = 1
    cur(2)(2) = 1
    cur(3)(1) = 1

    rep(N - 1) { x =>
      rep(4) { i =>
        rep(4) { j =>
          rep(x * 2 + 3) { k =>
            val pls =
              if (i == 1 || i == 2) {
                // BW
                // WB
                if (i == 1 && j == 2 || i == 2 && j == 1) 2
                // BB
                // WB
                else 0
              } else {
                // Ww
                // WB
                if (i != j) 1
                // Ww
                // WW
                else 0
              }

            if (k + pls <= 2000) next(j)(k + pls) = (next(j)(k + pls) + cur(i)(k)) % MOD
          }
        }
      }

      val t = cur
      cur = next
      next = t
      rep(4)(i => java.util.Arrays.fill(next(i), 0))
    }

    val ans = cur.map(_(K)).sum
    out.println(ans % MOD)
  }

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

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

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

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

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


The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.Each cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cell — left, right, down or up, respectively.The robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move.   If the robot moves beyond the edge of the board, it falls and breaks.  If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore). Robot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops.Determine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board).

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the test. Each test case's description is preceded by a blank line. Next is a line that contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2000$$$; $$$1 \le m \le 2000$$$) — the height and width of the board. This line followed by $$$n$$$ lines, the $$$i$$$-th of which describes the $$$i$$$-th line of the board. Each of them is exactly $$$m$$$ letters long and consists of symbols 'L', 'R', 'D' and 'U'. It is guaranteed that the sum of sizes of all boards in the input does not exceed $$$4\cdot10^6$$$.

For each test case, output three integers $$$r$$$, $$$c$$$ and $$$d$$$ ($$$1 \le r \le n$$$; $$$1 \le c \le m$$$; $$$d \ge 0$$$), which denote that the robot should start moving from cell $$$(r, c)$$$ to make the maximum number of moves $$$d$$$. If there are several answers, output any of them.

7

1 1
R

1 3
RRL

2 2
DL
RU

2 2
UD
RU

3 2
DL
UL
RU

4 4
RRRD
RUUD
URUD
ULLR

4 4
DDLU
RDDU
UUUU
RDLD

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

object Main extends App {
    val nums = readInt

    for (extended_loop <- 0 until nums) {
        val space = readLine
        val Array(n, m) = readLine.split(' ').map(_.toInt)
        var paths = ofDim[Int](n,m)
        //var path = ofDim[Boolean](n,m)
        for (i <- 0 until n; j <- 0 until m) {
            paths(i)(j) = 0
            //path(i)(j) = 0
        }
        var steps = ofDim[Char](n,m)
        // prev key, steps counter
        //var path = HashMap.empty[Int, (Int, Int)]

        for (i <- 0 until n) {
            val rows = readLine
            for (j <- 0 until rows.size){
                steps(i)(j) = rows(j)
            }
        }

        var mxm = 0
        var r = 0
        var d = 0
        for (i <- 0 until n; j <- 0 until m) {
            var curr_i = i
            var curr_j = j
            if (paths(i)(j) == 0) {
                var cnt = 0
                var stack = Stack[Int]()
                var prev_i = curr_i
                var prev_j = curr_j
                stack.push(prev_i*2000+prev_j)
                var stop_flg = false
                while (!stop_flg) {
                    if (paths(curr_i)(curr_j)<0) {
                        var past_part = cnt - paths(curr_i)(curr_j).abs
                        while (curr_i*2000 + curr_j != prev_i*2000 + prev_j) {
                            paths(prev_i)(prev_j) = past_part + 1
                            if (past_part + 1 > mxm) {
                                mxm = past_part + 1
                                r = prev_i
                                d = prev_j
                            }
                            var prev_value = stack.pop()
                            prev_i = prev_value/2000
                            prev_j = prev_value%2000
                        }
                        var st = cnt - past_part
                        while (st > 0) {
                            paths(prev_i)(prev_j) = cnt - st + 1
                            if (cnt - st + 1 > mxm) {
                                mxm = cnt - st + 1
                                r = prev_i
                                d = prev_j
                            }
                            var prev_value = stack.pop()
                            prev_i = prev_value/2000
                            prev_j = prev_value%2000
                            st -= 1
                        }
                        stop_flg = true
                    }
                    if (!stop_flg) {
                        stack.push(prev_i*2000 + prev_j)
                        paths(curr_i)(curr_j) = -(cnt + 1)
                        //path += (curr_i*2000 + curr_j -> (prev_i*2000 + prev_j, cnt+1))
                        prev_j = curr_j
                        prev_i = curr_i
                        if (steps(curr_i)(curr_j) == 'R') {
                            curr_j = curr_j + 1
                        } else if (steps(curr_i)(curr_j) == 'L') {
                            curr_j = curr_j - 1
                        } else if (steps(curr_i)(curr_j) == 'U') {
                            curr_i = curr_i - 1
                        } else {
                            curr_i = curr_i + 1
                        }
                        cnt += 1
                        var ignore_flg = false
                        if (!(0<=curr_i & curr_i<n & 0<=curr_j & curr_j<m)) {
                            ignore_flg = true
                            stop_flg = true
                            var st = cnt
                            while (cnt > 0) {
                                paths(prev_i)(prev_j) = st - cnt + 1
                                if (st - cnt + 1 > mxm) {
                                    mxm = st - cnt + 1
                                    r = prev_i
                                    d = prev_j
                                }
                                var prev_value = stack.pop()
                                prev_i = prev_value/2000
                                prev_j = prev_value%2000
                                cnt -= 1
                            }
                        }
                        if (!ignore_flg && (paths(curr_i)(curr_j) > 0)) {
                            stop_flg = true
                            var adding = paths(curr_i)(curr_j)
                            var kt = cnt
                            while (cnt > 0) {
                                paths(prev_i)(prev_j) = (kt - cnt + 1) + adding
                                if ((kt - cnt + 1) + adding > mxm) {
                                    mxm = (kt - cnt + 1) + adding
                                    r = prev_i
                                    d = prev_j
                                }
                                var prev_value = stack.pop()
                                prev_i = prev_value/2000
                                prev_j = prev_value%2000
                                cnt -= 1
                            }
                        }

                    }
                }
            }
        }

        r += 1
        d += 1
        println(f"$r $d $mxm")
    }
}


On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?

The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs.

On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.

NoteIn the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items.In the second example, he can buy all items as they will cost him [5, 10, 17, 22].In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it.

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

import scala.util.Sorting

/**
  * @author Arthur Gazizov (Cinarra Systems)
  *         Created on 24.06.17.
  */
object Main {
  def main(args: Array[String]): Unit = {
    var out: PrintWriter = null
    var in: CodeforcesReader = null
    out = new PrintWriter(new OutputStreamWriter(System.out))
    in = new CodeforcesReaderWithStringTokenizerImpl(new BufferedReader(new InputStreamReader(System.in)))
    IOUtils.init(in)
    val solver = new Solver()
    solver.solve(1, in, out)
    in.close()
    out.close()
  }

  class Solver {
    def calculateSum(cost: Array[Long], m: Int): Long = {
      var tmp = cost.clone()
      for (i <- cost.indices) {
        tmp(i) += (i + 1L) * m
      }
      Sorting.quickSort(tmp)
      var sum = 0L
      for (i <- 0 until m) {
        sum += tmp(i)
      }
      sum
    }

    def f(cost: Array[Long], m: Int, have: Long): Boolean = {
      calculateSum(cost, m) <= have
    }

    def solve(testNumber: Int, in: CodeforcesReader, out: PrintWriter): Unit = {
      val n = in.nextInt()
      val have = in.nextLong()
      val cost = IOUtils.nextLongArray(n)
      var hi = n
      var lo = 0
      while (hi - lo > 3) {
        var m = (hi + lo) / 2
        if (!f(cost, m, have)) {
          hi = m
        } else {
          lo = m
        }
      }
      while (lo < n && f(cost, lo + 1, have)) {
        lo += 1
      }
      out.print(lo + " " + calculateSum(cost, lo))
    }
  }

  class CodeforcesReaderWithStringTokenizerImpl(reader: BufferedReader) extends CodeforcesReader {
    private var tokenizer: StringTokenizer = _

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

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

    override def nextLong(): Long = {
      next().toLong
    }

    override def nextDouble(): Double = {
      next().toDouble
    }
    override def close(): Unit = {
      tokenizer = null
      reader.close()
    }
  }

  abstract class CodeforcesReader() extends Closeable {
    def next(): String

    def nextInt(): Int

    def nextLong(): Long

    def nextDouble(): Double
  }

  object IOUtils {
    private var in: CodeforcesReader = _

    def init(codeforcesReader: CodeforcesReader): Unit = {
      this.in = codeforcesReader
    }

    def nextIntArray(size: Int): Array[Int] = {
      val ret = new Array[Int](size)
      for (i <- ret.indices) {
        ret(i) = in.nextInt()
      }
      ret
    }

    def nextLongArray(size: Int): Array[Long] = {
      val ret = new Array[Long](size)
      for (i <- ret.indices) {
        ret(i) = in.nextLong()
      }
      ret
    }

    def nextDoubleArray(size: Int): Array[Double] = {
      val ret = new Array[Double](size)
      for (i <- ret.indices) {
        ret(i) = in.nextDouble()
      }
      ret
    }

    def nextStringArray(size: Int): Array[String] = {
      val ret = new Array[String](size)
      for (i <- ret.indices) {
        ret(i) = in.next()
      }
      ret
    }
  }

}


There is a special offer in Vasya's favourite supermarket: if the customer buys $$$a$$$ chocolate bars, he or she may take $$$b$$$ additional bars for free. This special offer can be used any number of times.Vasya currently has $$$s$$$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $$$c$$$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. Each of the next $$$t$$$ lines contains four integers $$$s, a, b, c~(1 \le s, a, b, c \le 10^9)$$$ — the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.

Print $$$t$$$ lines. $$$i$$$-th line should contain the maximum possible number of chocolate bars Vasya can get in $$$i$$$-th test.

NoteIn the first test of the example Vasya can buy $$$9$$$ bars, get $$$3$$$ for free, buy another bar, and so he will get $$$13$$$ bars.In the second test Vasya buys $$$1000000000$$$ bars and gets $$$1000000000000000000$$$ for free. So he has $$$1000000001000000000$$$ bars.

object CF1065A extends App {

  val t = readInt()

  (1 to t) foreach(n => {
    val Array(s, a, b, c) = readLine().split(" ").map(_.toLong)

    var count = s/c + ((s/c)/a)*b

    println(count)

  })
}

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 t = ni()
    rep(t) { _ =>
      val s, a, b, c = nl()
      val d = s / c
      val ans = (d / a) * b + d
      out.println(ans)
    }
  }

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

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

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

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

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


Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.Print the minimum cost Vladik has to pay to get to the olympiad.

The first line contains three integers n, a, and b (1 ≤ n ≤ 105, 1 ≤ a, b ≤ n) — the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach.  The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.

Print single integer — the minimum cost Vladik has to pay to get to the olympiad.

NoteIn the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1. In the second example Vladik can fly directly from the airport 5 to the airport 2, because they belong to the same company.

import scala.collection.mutable

object A extends App {
  def readInts = readLine().split(" ").map(_.toInt)

  val Array(n, a, b) = readInts
  val s = readLine

  val c1 = s(a-1)
  val c2 = s(b-1)

  if (c1 == c2) println("0") else println("1")
}

object A743 {

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

  def main(args: Array[String]): Unit = {
    var Array(n,a,b) = readInts(3)
    a -= 1
    b -= 1
    val in = read
    if(in(a) == in(b))
      println("0")
    else
      println("1")
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object _743A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n, a, b = read[Int]
    val airports = read[String]
    val start = airports(a - 1)
    val end = airports(b - 1)

    val ans = if (start == end) 0 else 1

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object A_384 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.sa2)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line1 = readLine
    val n = line1.int
    val a = line1.int
    val b = line1.int

    val line2 = readLine.string

    val res = if (line2(a-1) == line2(b-1)) 0 else 1

    outLn(res)
    finish
  }

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

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

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

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

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

val sa1 = """
4 1 4
1010
"""

val sa2 = """
5 5 2
10110
"""

val sa3 = """
"""
}

}

import scala.io.StdIn.readLine

object A extends App {

  val Array(n, a, b) = readLine.split("\\s+").map(_.toInt - 1)

  val airports = readLine.map(e => if (e == '0') 0 else 1)

  val sameAirport = airports(a) == airports(b)

  val result = if (sameAirport) 0 else 1

  println(result)

}

import scala.io.StdIn.readLine

object A  extends App{

  val Array(n: Int, a: Int, b: Int) = readLine().split("\\s+").map(_.toInt - 1)

//  val airports = readLine.map(_.toInt)
  val airports = readLine.map(e => if ( e == '0') 0 else 1)

//  println(s"n $n  a: $a   b: $b")
//  println(airports.mkString(","))

  val sameAirport = airports(a) == airports(b)
//  println(s"sameAriport: $sameAirport")

  if (sameAirport)
    println(0)
  else {
    val start = a min b
    val stop = a max b
//    println(s"start: $start, stop: $stop")

    val trip = (airports.drop(start)).dropRight(n - stop)
//   println(trip.mkString(","))

    val c1 = trip.head
    val c2 = trip.last
    val cost1 = trip.indexOf(c2)
    val cost2 = trip.reverse.indexOf(c1)
    println( cost1 min cost2)
  }
}

import scala.io.StdIn.readLine

object A  extends App{

  val Array(n: Int, a: Int, b: Int) = readLine().split("\\s+").map(_.toInt - 1)

  val airports = readLine.map(_.toInt)

//  println(s"n $n  a: $a   b: $b")
//  println(airports.mkString(","))

  val sameAirport = airports(a) == airports(b)
//  println(s"sameAriport: $sameAirport")

  if (sameAirport)
    println(0)
  else {
    val start = a min b
    val stop = a max b
//    println(s"start: $start, stop: $stop")

    val trip = airports.drop(start).dropRight(n + 1 - stop)
//    println(trip.mkString(","))

    val c1 = trip.head
    val c2 = trip.last
    val cost1 = trip.indexOf(c2)
    val cost2 = trip.reverse.indexOf(c1)
    println( cost1 min cost2)
  }
}

import scala.io.StdIn.readLine

object A  extends App{

  val Array(n: Int, a: Int, b: Int) = readLine().split("\\s+").map(_.toInt - 1)

  val airports = readLine.map(_.toInt)

  val sameAirport = airports(a) == airports(b)

  if (sameAirport)
    println(0)
  else {
    val start = a min b
    val stop = a max b
    val trip = airports.drop(start).dropRight(n - stop)
    val c1 = trip.head
    val c2 = trip.last
    val cost1 = trip.indexOf(c2)
    val cost2 = trip.reverse.indexOf(c1)
    println( cost1 min cost2)
  }
}


Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:  Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.  Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string s, and the algorithm works as follows:  If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string.  If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.

The first line contains a non-empty string s.  It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.

In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.

NoteIn the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.In the second test the transformation will be like this:  string "yxyxy" transforms into string "xyyxy";  string "xyyxy" transforms into string "xyxyy";  string "xyxyy" transforms into string "xxyyy";  string "xxyyy" transforms into string "xyy";  string "xyy" transforms into string "y". As a result, we've got string "y". In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val x = line.count(_ == 'x')
  val y = line.length - x

  println("x" * (x - y) + "y" * (y - x))
}

object Main {
  def main(args: Array[String]) {
    val s = readLine()
    val xs = s.count(_ == 'x')
    val ys = s.count(_ == 'y')

    println("x" * (xs - ys) + "y" * (ys - xs))
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  println(line.replaceAll("yx", "").replaceAll("xy", ""))
}


Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9.

The first line contains number m (2 ≤ m ≤ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≤ xi ≤ 109, 0 ≤ yi ≤ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place.

In the only line print the answer to the problem.

import scala.collection._

object B extends App {

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

  val Array(m) = readInts(1)

  val map = mutable.Map.empty[(Int, Int), Int]
  val xs, ys = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    xs(i) = x
    ys(i) = y
    map.put((x, y), i)
  }

  def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {
    map.contains(x0, y0) && (
        !((map.contains(x0 - 1, y) && x0 - 1 != x) ||
          (map.contains(x0, y) && x0 != x) ||
          (map.contains(x0 + 1, y) && x0 + 1 != x)))
  }

  def canRemove(x: Int, y: Int): Boolean = {
    map.contains(x, y) &&
    (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))
  }

  val candidates = new java.util.TreeSet[Int]
  for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)

  var step = 0
  val digits = Array.ofDim[Int](m)

  while (!candidates.isEmpty()) {
    step += 1
    val c = if (step % 2 == 1) candidates.last else candidates.first
    digits(m - step) = c
    candidates.remove(c)
    val x = xs(c)
    val y = ys(c)
    map.remove(x, y)
    if (!canRemove(x - 1, y) && map.contains(x - 1, y)) candidates.remove(map(x - 1, y))
    if (!canRemove(x + 1, y) && map.contains(x + 1, y)) candidates.remove(map(x + 1, y))
    if (!canRemove(x - 2, y) && map.contains(x - 2, y)) candidates.remove(map(x - 2, y))
    if (!canRemove(x + 2, y) && map.contains(x + 2, y)) candidates.remove(map(x + 2, y))
    if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))
    if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))
    if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))
  }

  val MOD = 1000000009
  var res = 0L
  var mult = 1L
  for (d <- digits) {
    res = (res + d * mult) % MOD
    mult = mult * m % MOD
  }

  println(res % MOD)
}

import scala.collection._

object B extends App {

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

  val Array(m) = readInts(1)

  val map = mutable.Map.empty[(Int, Int), Int]
  val xs, ys = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    xs(i) = x
    ys(i) = y
    map.put((x, y), i)
  }

  def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {
    map.contains(x0, y0) && (!map.contains(x - 1, y) && !map.contains(x + 1, y))
  }

  def canRemove(x: Int, y: Int): Boolean = {
    map.contains(x, y) &&
    (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))
  }

  val candidates = new java.util.TreeSet[Int]
  for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)

  var step = 0
  val digits = Array.ofDim[Int](m)

  while (!candidates.isEmpty()) {
    step += 1
    val c = if (step % 2 == 1) candidates.last else candidates.first
    digits(m - step) = c
    candidates.remove(c)
    val x = xs(c)
    val y = ys(c)
    map.remove(x, y)
    if (canRemove(x - 1, y)) candidates.add(map(x - 1, y))
    if (canRemove(x + 1, y)) candidates.add(map(x + 1, y))
    if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))
    if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))
    if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))
  }

  val MOD = 1000000009
  var res = 0L
  var mult = 1L
  for (d <- digits) {
    res = (res + d * mult) % MOD
    mult = mult * m % MOD
  }

  println(res % MOD)
}

import scala.collection._

object B extends App {

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

  val Array(m) = readInts(1)

  val map = mutable.Map.empty[(Int, Int), Int]
  val xs, ys = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    xs(i) = x
    ys(i) = y
    map.put((x, y), i)
  }

  def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {
    map.contains(x0, y0) && (!map.contains(x - 1, y) && !map.contains(x + 1, y))
  }

  def canRemove(x: Int, y: Int): Boolean = {
    map.contains(x, y) &&
    (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))
  }

  val candidates = new java.util.TreeSet[Int]
  for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)

  var step = 0
  val digits = Array.ofDim[Int](m)

  while (!candidates.isEmpty()) {
    step += 1
    val c = if (step % 2 == 1) candidates.last else candidates.first
    digits(m - step) = c
    candidates.remove(c)
    val x = xs(c)
    val y = ys(c)
    map.remove(x, y)
    if (!canRemove(x - 1, y) && map.contains(x - 1, y)) candidates.remove(map(x - 1, y))
    if (!canRemove(x + 1, y) && map.contains(x + 1, y)) candidates.remove(map(x + 1, y))
    if (!canRemove(x - 2, y) && map.contains(x - 2, y)) candidates.remove(map(x - 2, y))
    if (!canRemove(x + 2, y) && map.contains(x + 2, y)) candidates.remove(map(x + 2, y))
    if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))
    if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))
    if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))
  }

  val MOD = 1000000009
  var res = 0L
  var mult = 1L
  for (d <- digits) {
    res = (res + d * mult) % MOD
    mult = mult * m % MOD
  }

  println(res % MOD)
}

import scala.collection._

object B extends App {

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

  val Array(m) = readInts(1)

  val map = mutable.Map.empty[(Int, Int), Int]
  val xs, ys = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    xs(i) = x
    ys(i) = y
    map.put((x, y), i)
  }

  def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {
    map.contains(x0, y0) && !map.contains(x - 1, y) && !map.contains(x + 1, y)
  }

  def canRemove(x: Int, y: Int): Boolean = {
    map.contains(x, y) &&
    (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))
  }

  val candidates = new java.util.TreeSet[Int]
  for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)

  var step = 0
  val digits = Array.ofDim[Int](m)

  while (!candidates.isEmpty()) {
    step += 1
    val c = if (step % 1 == 0) candidates.last else candidates.first
    digits(m - step) = c
    candidates.remove(c)
    val x = xs(c)
    val y = ys(c)
    map.remove(x, y)
    if (canRemove(x - 1, y)) candidates.add(map(x - 1, y))
    if (canRemove(x + 1, y)) candidates.add(map(x + 1, y))
    if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))
    if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))
    if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))
  }

  val MOD = 1000000009
  var res = 0L
  var mult = 1L
  for (d <- digits) {
    res = (res + d * mult) % MOD
    mult = mult * m % MOD
  }

  println(res % MOD)
}

import scala.collection._

object B extends App {

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

  val Array(m) = readInts(1)

  val map = mutable.Map.empty[(Int, Int), Int]
  val xs, ys = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(x, y) = readInts(2)
    xs(i) = x
    ys(i) = y
    map.put((x, y), i)
  }

  def dependsOn(x0: Int, y0: Int, x: Int, y: Int): Boolean = {
    map.contains(x0, y0) && (!map.contains(x - 1, y) && !map.contains(x + 1, y))
  }

  def canRemove(x: Int, y: Int): Boolean = {
    map.contains(x, y) &&
    (!dependsOn(x - 1, y + 1, x, y) && !dependsOn(x, y + 1, x, y) && !dependsOn(x + 1, y + 1, x, y))
  }

  val candidates = new java.util.TreeSet[Int]
  for (i <- 0 until m) if (canRemove(xs(i), ys(i))) candidates.add(i)

  var step = 0
  val digits = Array.ofDim[Int](m)

  while (!candidates.isEmpty()) {
    step += 1
    var c = if (step % 2 == 1) candidates.last else candidates.first
    if (c == 0 && step % 2 == 0) {
      candidates.remove(0)
      if (!candidates.isEmpty()) {
        c = candidates.first
        candidates.add(0)
      }
    }
    digits(m - step) = c
    candidates.remove(c)
    val x = xs(c)
    val y = ys(c)
    map.remove(x, y)
    if (!canRemove(x - 1, y) && map.contains(x - 1, y)) candidates.remove(map(x - 1, y))
    if (!canRemove(x + 1, y) && map.contains(x + 1, y)) candidates.remove(map(x + 1, y))
    if (!canRemove(x - 2, y) && map.contains(x - 2, y)) candidates.remove(map(x - 2, y))
    if (!canRemove(x + 2, y) && map.contains(x + 2, y)) candidates.remove(map(x + 2, y))
    if (canRemove(x - 1, y - 1)) candidates.add(map(x - 1, y - 1))
    if (canRemove(x, y - 1)) candidates.add(map(x, y - 1))
    if (canRemove(x + 1, y - 1)) candidates.add(map(x + 1, y - 1))
  }

  val MOD = 1000000009
  var res = 0L
  var mult = 1L
  for (d <- digits) {
    res = (res + d * mult) % MOD
    mult = mult * m % MOD
  }

  println(res % MOD)
}