using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using Pi = Pair<int, int>;

class Solver
{
    public void Solve(Scanner sc)
    {
        long A, B, n, x;
        sc.Make(out A, out B, out n, out x);
        if (A == 1) Fail((x + (ModInt)B * n));
        ModInt res = ModInt.Pow(A, n)*x;
        res += B * (1 - ModInt.Pow(A, n)) / (1 - A);
        WriteLine(res);
    }
}

public struct ModInt
{
    public const long MOD = (int)1e9 + 7;
    //public const long MOD = 998244353;
    public long Value { get; set; }
    public ModInt(long n = 0) { Value = n; }
    private static ModInt[] fac;//i!
    private static ModInt[] inv;//1/i
    private static ModInt[] facinv;//1/(i!)
    public override string ToString() => Value.ToString();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator +(ModInt l, ModInt r)
    {
        l.Value += r.Value;
        if (l.Value >= MOD) l.Value -= MOD;
        return l;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator -(ModInt l, ModInt r)
    {
        l.Value -= r.Value;
        if (l.Value < 0) l.Value += MOD;
        return l;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator *(ModInt l, ModInt r) => new ModInt(l.Value * r.Value % MOD);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt operator /(ModInt l, ModInt r) => l * Pow(r, MOD - 2);
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static implicit operator long(ModInt l) => l.Value;
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static implicit operator ModInt(long n)
    {
        n %= MOD; if (n < 0) n += MOD;
        return new ModInt(n);
    }

    public static ModInt Pow(ModInt m, long n)
    {
        if (n == 0) return 1;
        if (n % 2 == 0) return Pow(m * m, n >> 1);
        else return Pow(m * m, n >> 1) * m;
    }

    public static void Build(int n)
    {
        fac = new ModInt[n + 1];
        facinv = new ModInt[n + 1];
        inv = new ModInt[n + 1];
        inv[1] = 1;
        fac[0] = fac[1] = 1;
        facinv[0] = facinv[1] = 1;
        for (var i = 2; i <= n; i++)
        {
            fac[i] = fac[i - 1] * i;
            inv[i] = MOD - inv[MOD % i] * (MOD / i);
            facinv[i] = facinv[i - 1] * inv[i];
        }
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt Fac(ModInt n) => fac[n];
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt Inv(ModInt n) => inv[n];
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt FacInv(ModInt n) => facinv[n];
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static ModInt Comb(ModInt n, ModInt r)
    {
        if (n < r) return 0;
        if (n == r) return 1;
        var calc = fac[n];
        calc = calc * facinv[r];
        calc = calc * facinv[n - r];
        return calc;
    }
}
#region Template
public static class Template
{
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        new Solver().Solve(new Scanner());
        Console.Out.Flush();
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid());
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static int MaxElement<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; }
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    //public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    //public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    //public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}
public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString() => $"{v1.ToString()} {v2.ToString()}";
    public void Deconstruct(out T1 a, out T2 b) { a = v1; b = v2; }
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString() => $"{base.ToString()} {v3.ToString()}";
    public void Deconstruct(out T1 a, out T2 b, out T3 c) { Deconstruct(out a, out b); c = v3; }
}
#endregion


using System;

class Program
{

    static void Main(string[] args)
    {
        int n, m;
        string[] input = Console.ReadLine().Split(' ');
        n = int.Parse(input[0]);
        m = int.Parse(input[1]);
        long res = 1;
        const long d = 1000000009;
        for (long t = 2; m > 0; m /= 2, t = (t * t) % d)
        {
            if (m % 2 == 1)
                res = (res * t) % d;
        }
        res--;
        long ans = 1;
        for (int i = 0; i < n; i++)
        {
            ans *= res;
            ans %= 1000000009;
            if (res > 0)
                res--;
        }
        Console.WriteLine(ans);
        Console.ReadLine();
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace Codeforces
{
    class A
    {
        private static ThreadStart s_threadStart = new A().Go;
        private static bool s_time = false;

        long mod = 1000000009;

        private void Go()
        {
            int n = GetInt();
            int m = GetInt();

            long ans = 1;
            long k = 1;
            for (int i = 0; i < m; i++)
            {
                k = (k * 2) % mod;
            }
            k--;
            for (int i = 0; i < n; i++)
            {
                ans = (ans * k) % mod;
                k--;
            }

            Wl(ans);
        }

        #region Template

        public static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            Thread main = new Thread(new ThreadStart(s_threadStart), 512 * 1024 * 1024);
            timer.Start();
            main.Start();
            main.Join();
            timer.Stop();
            if (s_time)
                Wl(timer.ElapsedMilliseconds);
        }

        private static IEnumerator<string> ioEnum;
        private static string GetString()
        {
            while (ioEnum == null || !ioEnum.MoveNext())
            {
                ioEnum = Console.ReadLine().Split().AsEnumerable().GetEnumerator();
            }

            return ioEnum.Current;
        }

        private static int GetInt()
        {
            return int.Parse(GetString());
        }

        private static long GetLong()
        {
            return long.Parse(GetString());
        }

        private static double GetDouble()
        {
            return double.Parse(GetString());
        }

        private static List<int> GetIntArr(int n)
        {
            List<int> ret = new List<int>(n);
            for (int i = 0; i < n; i++)
            {
                ret.Add(GetInt());
            }
            return ret;
        }

        private static void Wl<T>(T o)
        {
            if (o is double)
            {
                Wld((o as double?).Value, "");
            }
            else if (o is float)
            {
                Wld((o as float?).Value, "");
            }
            else
                Console.WriteLine(o.ToString());
        }

        private static void Wl<T>(IEnumerable<T> enumerable)
        {
            Wl(string.Join(" ", enumerable.Select(e => e.ToString()).ToArray()));
        }

        private static void Wld(double d, string format)
        {
            Wl(d.ToString(format, CultureInfo.InvariantCulture));
        }

        public struct Tuple<T, K> : IComparable<Tuple<T, K>>
            where T : IComparable<T>
            where K : IComparable<K>
        {
            public T Item1;
            public K Item2;

            public Tuple(T t, K k)
            {
                Item1 = t;
                Item2 = k;
            }

            public override bool Equals(object obj)
            {
                var o = (Tuple<T, K>)obj;
                return o.Item1.Equals(Item1) && o.Item2.Equals(Item2);
            }

            public override int GetHashCode()
            {
                return Item1.GetHashCode() ^ Item2.GetHashCode();
            }

            public override string ToString()
            {
                return "(" + Item1 + " " + Item2 + ")";
            }

            #region IComparable<Tuple<T,K>> Members

            public int CompareTo(Tuple<T, K> other)
            {
                int ret = Item1.CompareTo(other.Item1);
                if (ret != 0) return ret;
                return Item2.CompareTo(other.Item2);
            }

            #endregion
        }

        #endregion
    }
}


// Problem: 859B - Lazy Security Guard
// Author: Gusztav Szmolik

using System;

class LazySecurityGuard
    {
    static int Main ()
        {
        string[] words = ReadSplitLine (1);
        if (words == null)
            return -1;
        uint n;
        if (!UInt32.TryParse (words[0], out n))
            return -1;
        if (n < 1 || n > 1000000)
            return -1;
        ushort a = 1;
        ushort aNext = 2;
        while (aNext*aNext <= n)
            {
            a = aNext;
            aNext++;
            }
        ushort r = Convert.ToUInt16 (n-a*a);
        ushort ans = Convert.ToUInt16 (r == 0 ? 4*a : (r > a ? 4*a+4 : 4*a+2));
        Console.WriteLine (ans);
        return 0;
        }

    static string[] ReadSplitLine (uint numWordNeed)
        {
        string line = Console.ReadLine ();
        if (line == null)
            return null;
        char[] delims = new char[2] {' ', '\t'};
        string[] words = line.Split (delims,StringSplitOptions.RemoveEmptyEntries);
        return (words.Length == numWordNeed ? words : null);
        }
    }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            double n = double.Parse(Console.ReadLine());

            double k = Math.Ceiling(Math.Sqrt(n));

            double s = Math.Floor(n / k);

            double res = 0;

            if ( n-k*s!=0       )
            {
                res = (k * 2 + s * 2) + 2;
            }
            else
            {
                res = (k * 2 + s * 2);
            }

            Console.WriteLine(res);

              // while (Console.ReadKey().Key != ConsoleKey.Enter) ;

        }
    }
}


using System;

namespace HeidiLearnsHashingEasy
{
    class Program
    {
        static void Main(string[] args)
        {
            string input;
            long r;
            long x, y;

            while (true)
            {
                input = Console.ReadLine();

                if (string.IsNullOrEmpty(input)) break;

                r = long.Parse(input);

                if (r % 2 == 0)
                {
                    Console.WriteLine("NO");
                }
                else
                {
                    x = 1;
                    y = (r - 3) / 2;

                    if (y <= 0)
                        Console.WriteLine("NO");
                    else
                        Console.WriteLine("{0} {1}", x, y);
                }
            }
        }
    }
}


using System;
using System.IO;
using System.Collections.Generic;

namespace _262
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.SetIn(new StreamReader("input.txt"));

            solve_helvetic2019A1_improved();
            //solve_262A();
        }

        /*
        In the tutorial it is mentioned that
        we are solving linear equation with one variable.

        Although it looks like a quadratic equation at first sight
        in reality it is a hidden linear equation.
        we just need to carefully analyse it and figure out
        that we don't always have equations in a clean canonical ways.
        like ax + b = 0.

        in the given equation:
        r = x^2 + 2xy + x + 1
        we could ajust it like that:
        r - x^2 - x - 1 = 2xy

        And this part brings confusion. Because the right part 2xy
        is not just y but also multiplied by 2x.
        TODO: Make description cleaner

         */
        public static void solve_helvetic2019A1_improved()
        {
            long r = Convert.ToInt64(Console.ReadLine());

            for (int x = 1; x < Math.Sqrt(r); x++)
            {
                long y = r - x * x - x - 1;

                if (y > 0 && y % 2 * x == 0)
                {
                    Console.WriteLine("{0} {1}", x, y / 2 * x);

                    return;
                }
            }

            Console.WriteLine("NO");
        }

        /*
        В первом варианте, я пытался тупо двойным циклом найти одновременно
        x и y. Но даже если учесть что в первом цикле у нас будет sqrt(r) итераций
        для нахождения x, то вторым циклом мы не сможем в рамках ограничения по времени задачи
        найти y.
         */
        public static void solve_helvetic2019A1()
        {
            long r = Convert.ToInt64(Console.ReadLine());

            bool found = false;
            long x = 0;
            long y = 0;
            long xLen = (int)Math.Sqrt(r);
            for (x = 1; x < xLen; x++)
            {
                long yLen = r <= 100000 ? r : r / (2 * xLen);
                for (y = 2 * x + 1; y < yLen; y++)
                {
                    long h = x * x + 2 * x * y + x + 1;
                    if (h > r)
                    {
                        break;
                    }

                    if (r == h)
                    {
                        found = true;
                        break;
                    }
                }

                if (found)
                {
                    break;
                }
            }

            if (found)
            {
                Console.Write("{0} {1}", x, y);
            }
            else
            {
                Console.Write("NO");
            }
        }

        public static void solve_262A()
        {
            string[] nm = Console.ReadLine().Split(' ');

            int n = Convert.ToInt32(nm[0]);
            int m = Convert.ToInt32(nm[1]);

            int bought = n;
            int max = n;
            while (bought > 0)
            {
                bought = max % m == 0 ? (bought + m - 1) / m : bought / m;
                max += bought;
            }
            Console.WriteLine(max);
        }

        /*
1)4
2)1 + (1 + 1) + (1 + 1)
3)1 + (1 + 1 + 1)
4)1

1 1

2 3

3 7

4 14

5 25

1)5
2)1 + (1 + 1) + (1 + 1) + (1 + 1)
3)1 + (1 + 1 + 1) + (1 + 1 + 1)
4)1 + (1 + 1 + 1 + 1)
5)1

(0) + 1 => (1) + 2 => (1 + 3) + 3 => (3 + 7) + 4 => (7 + 14) + 5
         */
        public static void solve_164B()
        {
            int n = Convert.ToInt32(Console.ReadLine());

            int total = 0;
            int prev = 0;
            int prevPrev = 0;
            for (int i = 1; i <= n; i++)
            {
                total = prevPrev + prev + i;

                prevPrev = prev;
                prev = total;
            }

            Console.WriteLine(total);
        }

        /*
        Внимание: в данной задаче если крот нажал на кнопку q и было смещение вправо.
        То есть надо восстановить, сместив букву влево, то у нас будет исключение.
        Потомучто в строке keyboard q это первая буква строки. И левее нее у нас ничего нет.
        НО! По условию у нас нигде не сказано, что если крот нажал на самую левую клавишу, то
        мы должны восстановить сообщение взяв самую правую букву. Циклический сдвиг замкнутость.
        То есть такой кейс не рассматривается.

        Для ускорения алгоритма, можно избавиться от встроенной проверки символа IndexOf и запихать
        все буквы в словарь. Где буквы будут ключами, а их значение индексом в строке.
         */
        public static void solve_271A()
        {
            string direction = Console.ReadLine();
            string text = Console.ReadLine();

            string keyboard = "qwertyuiopasdfghjkl;zxcvbnm,./";

            string answer = String.Empty;
            if (direction == "R")
            {
                for (int i = 0; i < text.Length; i++)
                {
                    answer += keyboard[keyboard.IndexOf(text[i]) - 1];
                }
            }
            else
            {
                for (int i = 0; i < text.Length; i++)
                {
                    answer += keyboard[keyboard.IndexOf(text[i]) + 1];
                }
            }

            Console.WriteLine(answer);
        }

        /*
        Данный алгоритм можно еще улучшить, если избавиться от встроенной провекри на символ
        String.Contains.
        и использовать встроенную структуру данных dictionary с проверокой значения за хотя бы
        log(n)
         */
        public static void solve_368A()
        {
            string[] nm = Console.ReadLine().Split(' ');

            int n = Convert.ToInt32(nm[0]);
            int m = Convert.ToInt32(nm[1]);

            int count = 0;
            string noir = "WBG";
            for (int i = 0; i < n; i++)
            {
                string[] row = Console.ReadLine().Split(' ');

                for (int j = 0; j < m; j++)
                {
                    if (noir.Contains(row[j]))
                    {
                        count++;
                    }
                }
            }

            string answer =  (count == n * m) ? "#Black&White" : "#Color";

            Console.WriteLine(answer);
        }

        public static void solve_90A()
        {
            string[] abn = Console.ReadLine().Split(' ');

            int a = Convert.ToInt32(abn[0]);
            int b = Convert.ToInt32(abn[1]);
            int n = Convert.ToInt32(abn[2]);

            int count = 1;
            while (n > 0)
            {
                if (count % 2 == 0)
                {
                    n -= gcd(n, b);
                }
                else
                {
                    n -= gcd(n, a);
                }

                count++;
            }

            int answer = (--count % 2 == 0) ? 1 : 0;

            Console.WriteLine(answer);
        }

        public static int gcd(int a, int b)
        {
            if (b == 0)
            {
                return a;
            }

            return gcd(b, a % b);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            char ch = 't';
            string str = "";
            while (ch != ' ')
            {
                ch = Convert.ToChar(Console.Read());
                str = str + ch;
            }
            long a = Int64.Parse(str);
            long m = Convert.ToInt64(Console.ReadLine());
            long z = 0;
            for (int i = 1; i < m; i++)
            {
                z = a % m;
                a = a + z;
            }
            if (z == 0) Console.WriteLine("Yes");
            else Console.WriteLine("No");
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Igranje.CF276
{
    class ProblemA
    {
        public static void Main(string [] varg)
        {
            string[] tokens = Console.ReadLine().Split(new char[] {' '});
            int a = int.Parse(tokens[0]);
            int m = int.Parse(tokens[1]);

            int sum = a;
            for (int i = 0; i < m; i++)
            {
                int deltasum = sum%m;
                if ( deltasum == 0)
                {
                    Console.WriteLine("Yes");
                    return;
                }
                sum = sum + deltasum;
                sum = sum%m;
            }
            Console.WriteLine("No");

        }
    }
}


using System;
using System.Text;

namespace ConsoleApp
{
    public class Program
    {
        private static int[] dp;
        public static void Main()
        {
            int n = Convert.ToInt32(Console.ReadLine());
            if (n == 0)
            {
                Console.WriteLine(0);
                return;
            }
            if (n < 10)
            {
                Console.WriteLine(1);
                return;
            }
            dp = new int[n + 1];
            for (int i = 10; i <= n; i++)
            {
                int temp = i;
                int min = Int32.MaxValue;
                while (temp > 0)
                {
                    int digit = temp % 10;
                    if (digit != 0 && dp[i - digit] < min)
                    {
                        min = dp[i - digit];
                    }
                    temp /= 10;
                }
                dp[i] = min + 1;
            }
            Console.WriteLine(dp[n] + 1);
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;

namespace C1
{
    static class RW
    {
        public static ulong RIntStdin()
        {
            // Read ONE integer, infinite input
            ulong res = 0;
            int symb = Console.Read();
            while ((symb < '0') || (symb > '9'))
            {
                symb = Console.Read();
            }
            while ((symb >= '0') && (symb <= '9'))
            {
                res = 10 * res + (ulong)symb - '0';
                symb = Console.Read();
            }
            return res;
        }
    }
    class Solution
    {
        ulong n;
        uint s;
        Dictionary<ulong, uint> d;
        public Solution()
        {
            n = RW.RIntStdin();
            d = new Dictionary<ulong, uint>();
        }
        public void EvalN(ulong num, uint steps)
        {
            int[] digits = new int[10];
            ulong copy = num;
            ulong novy_key;
            uint prev_steps;
            while (copy > 0)
            {
                digits[copy % 10]++;
                copy /= 10;
            }
            for (int i = 0; i < digits.Length; i++)
            {
                if (digits[i] > 0)
                {
                    novy_key = n - (ulong)i;
                    if (!d.ContainsKey(novy_key))
                    {
                        d.Add(novy_key, steps + 1);
                    }
                    else
                    {
                        d.TryGetValue(novy_key, out prev_steps);
                        if (prev_steps > steps + 1)
                        {
                            d[novy_key] = steps + 1;
                        }
                    }
                }
            }
        }
        public void Solve()
        {
            d.Add(n, 0);
            while (n > 0)
            {
                if (d.ContainsKey(n))
                {
                    d.TryGetValue(n, out s);
                    EvalN(n, s);
                    d.Remove(n);
                }
                n--;
            }
            uint r;  d.TryGetValue(0, out r); // result
            Console.WriteLine(r);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Solution s = new Solution();
            s.Solve();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.IO;
using System.Globalization;
using System.Collections;

namespace Task
{

    #region MyIo

    internal class MyIo : IDisposable
    {
        private readonly TextReader inputStream;
        private readonly TextWriter outputStream = Console.Out;

        private string[] tokens;
        private int pointer;

        public MyIo()
#if  LOCAL_TEST
            : this(new StreamReader("input.txt"))
#else
            : this(System.Console.In)
#endif
        {

        }

        public MyIo(TextReader inputStream)
        {
            this.inputStream = inputStream;
        }

        public string NextLine()
        {
            try
            {
                return inputStream.ReadLine();
            }
            catch (IOException)
            {
                return null;
            }
        }

        public string NextString()
        {
            try
            {
                while (tokens == null || pointer >= tokens.Length)
                {
                    tokens = NextLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    pointer = 0;
                }
                return tokens[pointer++];
            }
            catch (IOException)
            {
                return null;
            }
        }

        public int NextInt()
        {
            return Next<int>();
        }

        public long NextLong()
        {
            return Next<long>();
        }

        public T Next<T>()
        {
            return (T)Convert.ChangeType(NextString(), typeof(T));
        }

        public IEnumerable<T> NextSeq<T>(int n)
        {
            for (int i = 0; i < n; i++)
                yield return Next<T>();
        }

        public void Print(string format, params object[] args)
        {
            outputStream.Write(string.Format(CultureInfo.InvariantCulture, format, args));
        }

        public void PrintLine(string format, params object[] args)
        {
            Print(format, args);

            outputStream.WriteLine();
        }

        public void Print(bool o)
        {
            Print(o ? "YES" : "NO");
        }

        public void PrintLine(bool o)
        {
            PrintLine(o ? "YES" : "NO");
        }

        public void Print<T>(T o)
        {
            outputStream.Write(o);
        }

        public void PrintLine<T>(T o)
        {
            outputStream.WriteLine(o);
        }

        public void Close()
        {
            inputStream.Close();
            outputStream.Close();
        }

        void IDisposable.Dispose()
        {
            Close();

#if  LOCAL_TEST
            Console.ReadLine();
#endif
        }
    }

    #endregion

    internal class Program
    {
        #region Program

        private readonly MyIo io;

        public Program(MyIo io)
        {
            this.io = io;
        }

        public static void Main(string[] args)
        {
            using (MyIo io = new MyIo())
            {
                new Program(io)
                    .Solve();
            }
        }

        public static class P
        {
            public static P<T1, T2> Create<T1, T2>(T1 key, T2 val)
            {
                return new P<T1, T2>(key, val);
            }
        }

        public class P<T1, T2>
        {
            private class PComparer : IComparer<P<T1, T2>>
            {
                private readonly bool? byKey;

                public PComparer(bool? byKey)
                {
                    this.byKey = byKey;
                }

                public int Compare(P<T1, T2> x, P<T1, T2> y)
                {
                    x = x ?? new P<T1, T2>();
                    y = y ?? new P<T1, T2>();

                    if (byKey == true)
                        return Comparer<T1>.Default.Compare(x.Key, y.Key);
                    else if (byKey == false)
                        return Comparer<T2>.Default.Compare(x.Value, y.Value);
                    else
                    {
                        var tr = Comparer<T1>.Default.Compare(x.Key, y.Key);

                        if (tr != 0)
                            tr = Comparer<T2>.Default.Compare(x.Value, y.Value);

                        return tr;
                    }
                }
            }

            public P()
            {
            }

            public P(T1 key, T2 val)
            {
                this.Key = key;
                this.Value = val;
            }

            public T1 Key
            {
                get;
                set;
            }

            public T2 Value
            {
                get;
                set;
            }

            public P<T1, T2> Clone()
            {
                return new P<T1, T2>(Key, Value);
            }

            public static IComparer<P<T1, T2>> KeyComparer
            {
                get { return new PComparer(true); }
            }

            public static IComparer<P<T1, T2>> ValueComparer
            {
                get { return new PComparer(false); }
            }

            public static implicit operator T1(P<T1, T2> obj)
            {
                return obj.Key;
            }

            public static implicit operator T2(P<T1, T2> obj)
            {
                return obj.Value;
            }

            public P<T1, T2> SetKey(T1 key)
            {
                Key = key;
                return this;
            }

            public P<T1, T2> SetValue(T2 value)
            {
                Value = value;
                return this;
            }

            public override string ToString()
            {
                return string.Format("Key: {0}, Value: {1}", Key, Value);
            }

            public override int GetHashCode()
            {
                int hash = 17;
                hash = hash * 31 + ((Equals(Key, default(T1))) ? 0 : Key.GetHashCode());
                hash = hash * 31 + ((Equals(Value, default(T1))) ? 0 : Key.GetHashCode());
                return hash;

            }
        }

        #endregion
        public const long MOD = 1000000007;
        public const double EPS = 1e-14;

        private void Solve()
        {
            var n = io.NextInt();
            var m = io.NextInt();

            var fi = io.NextSeq<int>(n).ToArray();

            var g = new P<int, int>[m];
            var g1 = new P<int, int>[m];

            var sk = Enumerable.Range(0, m).ToArray();
            var sk1 = Enumerable.Range(0, m).ToArray();
            var c = new int[n + 1];
            var c1 = new int[n + 1];

            for (int i = 0; i < m; i++)
            {
                var from = io.NextInt() - 1;
                var to = io.NextInt() - 1;

                g[i] = P.Create(from , to);
                c[from + 1]++;
                g1[i] = P.Create(to, from);
                c1[to + 1]++;
            }

            for (int i = 1; i <= n; i++)
            {
                c[i] += c[i - 1];
                c1[i] += c1[i - 1];
            }

            Array.Sort(sk, (i, i1) => P<int, int>.KeyComparer.Compare(g[i], g[i1]));

            Array.Sort(sk1, (i, i1) => P<int, int>.KeyComparer.Compare(g1[i], g1[i1]));

            var used = new bool[n];
            var used1 = new bool[n];

            for (int i = 0; i < n; i++)
            {
                if (fi[i] == 1)
                    BFS(g, sk, c, used, null, 0 , i);
            }

            for (int i = 0; i < n; i++)
            {
                if (fi[i] == 2)
                    BFS(g1, sk1, c1, used1, fi, 1, i);
            }

            for (int i = 0; i < n; i++)
            {
                io.PrintLine((used[i] && used1[i]) ? "1":"0");
            }
        }

        public void BFS(P<int, int>[] g, int[] sk, int[] c, bool[] used, int[] fi, int ifi, int s)
        {

            var n = c.Length;

            used = used ?? new bool[n];

            if (used[s])
                return;

            Queue<int> q = new Queue<int>();
            q.Enqueue(s);

            used[s] = true;

            while (q.Count > 0)
            {
                int v = q.Dequeue();
                for (var i = c[v]; i < c[v + 1]; i++)
                {
                    var to = g[sk[i]].Value;

                    if (used[to])
                        continue;

                    used[to] = true;

                    if (fi != null && fi[to] == ifi)
                        continue;

                    q.Enqueue(to);
                }
            }
        }

        public static void Shuffle<T>(IList<T> list)
        {
            var rnd = new Random(DateTime.Now.Millisecond);

            var n = list.Count;

            while (n > 1)
            {
                n--;
                var k = rnd.Next(n + 1);
                var value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }

    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace ConsoleApplication1 {
    struct Pair {
        public int X, Y;
        public Pair(int x, int y) {
            X = x;
            Y = y;
        }
        public override string ToString() {
            return string.Format("{0} {1}", X, Y);
        }
    }

    class Graph : List<List<int>> {
        public Graph(int num) : base(num) {
            for (int i = 0; i < num; i++) {
                this.Add(new List<int>());
            }
        }
    }

    class Program {
        static int n, m, k, t, ans;
        static TextReader input;
        static int[] f;
        static bool[] u1, u2;
        static Graph g, rg;
        static void Main(string[] args) {
#if TESTS
            Stopwatch sw = new Stopwatch();
            sw.Start();
            input = new StreamReader("input.txt");
#else
            input = Console.In;
#endif
            Solve();
#if TESTS
            Console.WriteLine();
            Console.WriteLine("Milliseconds: {0}", sw.ElapsedMilliseconds);
            Console.ReadLine();
#endif
        }

        #region read helpers
        public static int[] ReadIntArray() {
            return input.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
        }

        public static List<int> ReadIntList() {
            return input.ReadLine().Split(' ').Select(x => int.Parse(x)).ToList();
        }

        public static int ReadInt() {
            return int.Parse(input.ReadLine());
        }

        #endregion

        static void Solve() {
            int[] a = ReadIntArray();
            n = a[0];
            m = a[1];
            g = new Graph(n);
            rg = new Graph(n);
            u1 = new bool[n];
            u2 = new bool[n];
            f = ReadIntArray();
            for (int i = 0; i < m; i++) {
                int[] b = ReadIntArray();
                g[--b[0]].Add(--b[1]);
                rg[b[1]].Add(b[0]);
            }
            for (int i = 0; i < n; i++) {
                if (f[i] == 1 && !u1[i]) {
                    Bfs1(i);
                }
            }
            for (int i = 0; i < n; i++) {
                if (f[i] == 2 && !u2[i]) {
                    Bfs2(i);
                }
            }
            for (int i = 0; i < n; i++) {
                if (u1[i] && u2[i])
                    Console.WriteLine(1);
                else
                    Console.WriteLine(0);
            }
        }

        static void Bfs1(int v) {
            u1[v] = true;
            Queue<int> q = new Queue<int>();
            q.Enqueue(v);
            while (q.Count > 0) {
                int u = q.Dequeue();
                foreach (int i in g[u]) {
                    if (!u1[i]) {
                        u1[i] = true;
                        q.Enqueue(i);
                    }
                }
            }
        }

        static void Bfs2(int v) {
            u2[v] = true;
            Queue<int> q = new Queue<int>();
            q.Enqueue(v);
            while (q.Count > 0) {
                int u = q.Dequeue();
                foreach (int i in rg[u]) {
                    if (!u2[i]) {
                        u2[i] = true;
                        if (f[i] != 1)
                            q.Enqueue(i);
                    }
                }
            }
        }

        static void Dfs1(int v) {
            u1[v] = true;
            foreach (int i in g[v]) {
                if (!u1[i]) Dfs1(i);
            }
        }

        static void Dfs2(int v) {
            u2[v] = true;
            if (f[v] == 1) return;
            foreach (int i in rg[v]) {
                if (!u2[i]) Dfs2(i);
            }
        }

        static int[] Count_Sort(int[] a, int k) {
            int n = a.Length;
            int[] b = new int[n];
            int[] c = new int[k];
            for (int i = 0; i < n; ++i)
                ++c[a[i]];
            for (int i = 1; i < k; ++i)
                c[i] += c[i - 1];
            for (int i = n - 1; i >= 0; --i) {
                b[c[a[i]] - 1] = a[i];
                --c[a[i]];
            }
            return b;
        }

        static void Radix_Sort(int[] a, int k) {
            int n = a.Length;
            int repeats = 32 / k;
            int size = 1 << k;
            int mask = size - 1;
            for (int i = 0; i < repeats; ++i) {
                int[] c = new int[size];
                int[] b = new int[n];
                for (int j = 0; j < n; ++j) {
                    int r = (a[j] & (mask << (i * k))) >> (i * k);
                    ++c[r];
                }
                for (int j = 1; j < size; ++j)
                    c[j] += c[j - 1];
                for (int j = n - 1; j >= 0; --j) {
                    int r = (a[j] & (mask << (i * k))) >> (i * k);
                    b[c[r] - 1] = a[j];
                    --c[r];
                }
                Array.Copy(b, a, n);
            }
        }
    }

    public static class Extensions {
        public static void Print<T>(this IEnumerable<T> e) {
            foreach (T item in e) {
                Console.Write("{0} ", item);
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace mono
{
    public class Program
    {
        public static char res(int a, int b)
        {
            return a > b ? '+' : (a < b ? '-' : '0');
        }

        public static void Main(string[] args)
        {
            string s = Console.ReadLine();
            string[] arr = s.Split(new char[]{ ' ' });
            char c;
            Console.WriteLine((c = res(int.Parse(arr[0]) + int.Parse(arr[2]), int.Parse(arr[1]))) == res(int.Parse(arr[0]), int.Parse(arr[1]) + int.Parse(arr[2])) ? c : '?');
        }
    }
}


using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split(' ');
            int x=Convert.ToInt32(s[0]), y=Convert.ToInt32(s[1]), z=Convert.ToInt32(s[2]);
            if (x-y+z<0 && x-y-z<0) Console.WriteLine("-");
            if (x-y+z>0 && x-y-z>0) Console.WriteLine("+");
            if (x-y+z==0 && x-y-z==0) Console.WriteLine("0");
            if ((x-y+z>0 && x-y-z<0) || (x-y+z<0 && x-y-z>0) ||(x-y+z<0 && x-y-z==0) || (x-y+z>0 && x-y-z==0) || (x-y+z==0 && x-y-z>0) || (x-y+z==0 && x-y-z<0)) Console.WriteLine("?");

        }
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

public static class Intparser
{
    public static int ToInt32(this string text)
    {
        return Convert.ToInt32(text);
    }
    public static long ToInt64(this string text)
    {
        return Convert.ToInt64(text);
    }
}

class Program
{
    private static void Main(string[] args)
    {
        var ins = Console.ReadLine().Split(' ').Select(x => x.ToInt64()).ToArray();

        if (ins[0] >= ins[1])
        {

            var max = ins[1] / 2;

            if (ins[1] % 2 == 0)
                max--;

            Console.WriteLine(max);

        }
        else
        {
            var sub = ins[1] - ins[0];

            if (sub > ins[0])
            {
                Console.WriteLine(0);
            }
            else
            {
                sub = ins[0] - sub;
                sub = (sub / 2) + sub % 2;

                Console.WriteLine(sub);
            }
        }
    }
}


using System;
using System.Collections.Generic;

namespace Code_Force
{
    class Program
    {
        static void Main(string[] args)
        {
            string S = Console.ReadLine();
            long k = Int64.Parse(S.Remove(0, S.IndexOf(' ')));
            long n = Int64.Parse(S.Remove(S.IndexOf(' ')));
            if (n == .5 * (k + 1)&k!=1) Console.WriteLine(1);
            else if (n < .5 * (k + 1)) Console.WriteLine(0);
            else if (n >= k) Console.WriteLine((k - 1) / 2);
            else
            {
                long dif = k - n-1;
                Console.WriteLine(((k - 1) / 2)-dif);
            }
        }

    }
}


using System;
using System.IO;
using System.Linq;
using System.Text;

namespace TaskC
{
    class Program
    {
        static void Main(string[] args)
        {
            new Solver().Solve().OutputResult();
        }

        private class ExtendedReader : StreamReader
        {
            private static readonly char Separator = ' ';

            public ExtendedReader(Stream stream) : base(stream) { }
            public ExtendedReader(Stream stream, bool detectEncodingFromByteOrderMarks) : base(stream, detectEncodingFromByteOrderMarks) { }
            public ExtendedReader(Stream stream, Encoding encoding) : base(stream, encoding) { }
            public ExtendedReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) : base(stream, encoding, detectEncodingFromByteOrderMarks) { }
            public ExtendedReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) : base(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize) { }
            public ExtendedReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) : base(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen) { }
            public ExtendedReader(string path) : base(path) { }
            public ExtendedReader(string path, bool detectEncodingFromByteOrderMarks) : base(path, detectEncodingFromByteOrderMarks) { }
            public ExtendedReader(string path, Encoding encoding) : base(path, encoding) { }
            public ExtendedReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) : base(path, encoding, detectEncodingFromByteOrderMarks) { }
            public ExtendedReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) : base(path, encoding, detectEncodingFromByteOrderMarks, bufferSize) { }

            public char ReadChar()
            {
                return (char)this.Read();
            }

            public double ReadDoubleFromArray()
            {
                StringBuilder sb = new StringBuilder();
                char ch = this.ReadChar();
                while (ch != Separator && ch != '\n')
                {
                    sb.Append(ch);
                    ch = this.ReadChar();
                }
                return Convert.ToDouble(sb.ToString());
            }

            public int ReadInt()
            {
                return int.Parse(this.ReadLine());
            }

            public Int64 ReadInt64()
            {
                return Int64.Parse(this.ReadLine());
            }

            public int[] ReadIntArray()
            {
                return this.ReadLine().Split(' ').Select(int.Parse).ToArray();
            }

            public char[] ReadCharArray()
            {
                return this.ReadLine().ToCharArray();
            }

            public string ReadString()
            {
                return this.ReadLine();
            }

            public Int64[] ReadInt64Array()
            {
                return this.ReadLine().Split(Separator).Select(Int64.Parse).ToArray();
            }

            public Double[] ReadDoubleArray()
            {
                return this.ReadLine().Split(Separator).Select(Double.Parse).ToArray();
            }
        }

        private abstract class SolverBase
        {
            protected readonly ExtendedReader _reader;
            protected readonly TextWriter _writer;

            protected SolverBase()
            {
#if DEBUG
                _reader = new ExtendedReader(@"input.txt");
                //_writer = new StreamWriter(@"output.txt");
                _writer = new StreamWriter(Console.OpenStandardOutput());
#else
                _reader = new ExtendedReader(Console.OpenStandardInput());
                _writer = new StreamWriter(Console.OpenStandardOutput());
#endif
            }

            public abstract Solver Solve();

            public abstract void OutputResult();
        }

        private class Solver : SolverBase
        {
            private long result = -1L;

            public override Solver Solve()
            {
                // link to task: http://codeforces.com/contest/689/problem/C

                var m = _reader.ReadInt64();
                long lower = 1;
                long upper = (long)1e16;
                while (upper - lower > 1)
                {
                    long middle = (lower + upper) / 2;

                    var M = CalcM(middle);
                    if (M >= m)
                        upper = middle;
                    else
                        lower = middle;
                }

                if (CalcM(upper) == m)
                    result = upper;

                return this;
            }

            static long CalcM(long n)
            {
                long M = 0;
                for (long k = 2; k * k * k <= n; k++)
                {
                    M += n / (k * k * k);
                }
                return M;
            }

            public override void OutputResult()
            {
                string answer = result.ToString();

                _writer.WriteLine(answer);
                _writer.Dispose();
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static long calc(long med)
    {
        var calc = 0L;
        var st = 2;
        while (med / st / st / st > 0)
        {
            calc += med / st / st / st;
            st++;
        }
        return calc;
    }

    static void solve(StreamReader reader, StreamWriter writer)
    {
        long m = reader.ReadLong();
        var min = 1L;
        var max = (long)1e18;
        while (max - min > 1)
        {
            var med = (min + max)/2;
            var cl = calc(med);
            if (cl >= m)
                max = med;
            else
                min = med;
        }
        if (calc(min) == m)
            writer.WriteLine(min);
        else if (calc(max) == m)
            writer.WriteLine(max);
        else
            writer.WriteLine(-1);

        //int n = reader.ReadInt();
        //var a = new int[n+1];
        //var r = new int[n+1];
        //for (int i = 1; i <= n; ++i)
        //{
        //    a[i] = reader.ReadInt();
        //    r[i] = i-1;
        //}

        //for (int j = 1; j <= n; ++j)
        //{
        //    if (j < n)
        //        r[j+1] = Math.Min(r[j+1], r[j] + 1);
        //    r[a[j]] = Math.Min(r[a[j]], r[j] + 1);
        //}
        //for (int j = 1; j <= n; ++j)
        //{
        //    writer.Write(r[j] + " ");
        //}
    }

    #region launch
    static void Main(string[] args)
    {
        using (var writer = new FormattedStreamWriter(Console.OpenStandardOutput()))
        {
            using (var reader = new StreamReader(
#if CODECHIEF_LOCAL
    "input.txt"
#else
Console.OpenStandardInput()
#endif
))
            {
                solve(reader, writer);
            }
        }
    }
    #endregion
}

#region helpers
class FormattedStreamWriter : StreamWriter
{
    public FormattedStreamWriter(Stream stream)
        : base(stream)
    {
    }

    public override IFormatProvider FormatProvider
    {
        get
        {
            return CultureInfo.InvariantCulture;
        }
    }
}

static class IOExtensions
{
    public static string ReadString(this StreamReader reader)
    {
        return reader.ReadToken();
    }

    public static int ReadInt(this StreamReader reader)
    {
        return int.Parse(reader.ReadToken(), CultureInfo.InvariantCulture);
    }

    public static long ReadLong(this StreamReader reader)
    {
        return long.Parse(reader.ReadToken(), CultureInfo.InvariantCulture);
    }

    public static double ReadDouble(this StreamReader reader)
    {
        return double.Parse(reader.ReadToken(), CultureInfo.InvariantCulture);
    }

    static Queue<string> buffer = new Queue<string>(100);

    static string ReadToken(this StreamReader reader)
    {
        while (buffer.Count == 0)
        {
            reader.ReadLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach((t) =>
            {
                buffer.Enqueue(t);
            });
        }
        return buffer.Dequeue();
    }
}
#endregion


// done
/***************************************************************************
* Title : Almost Prime
* URL   : http://codeforces.com/problemset/problem/26/A
* Contst: Offline
* Date  : 2018-04-27
* Author: Atiq Rahman
* Comp  : O(N)
* Status: Accepted
* Notes : This is not really a good problem for practicing implementation of
*   doubly linked list. Building LinkedList is not trivial since nodes are out
*   of order.. we can say this place for practicing alternative doubly linked
*   list representation.
*
*   Applications of this problem:
*   Test Prime Number Generatation algorithm up to a small range (<=3000)
*
*   With this problem following Prime Generation Algos tested,
*   - Dynamic Programming Approach for generating primes
*   - Sieve of Eratosthenes
*
*   related: 'uva-online-judge/old/10699_Count the factors.cpp'
* meta  : tag-linked-list, tag-easy
***************************************************************************/
using System;
using System.Collections.Generic;

public class PrimeUtil {
  // The access level for class members and struct members, including nested
  // classes and structs, is private by default.
  // ref: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/
  // classes-and-structs/access-modifiers
  List<int> primes;
  System.Collections.BitArray isPrime;
  int n;

  // Divide each candidate number (starting from 6) by prime numbers to find
  // divisors. Keep dividing the number with the divisor/factor. Do it twice
  // and if the number comes down to one after those divisions we got an
  // almost prime
  public int FindAlmostPrimes()
  {
    int count = 0;

    for (int num = 6; num <= n; num++) {
      int firstPrimeDivisorIndex = GetPrimeFactor(num);
      if (firstPrimeDivisorIndex == -1)
        continue;
      // divide the number as long as it is divisible by factor
      int dNum = DivideDown(num, primes[firstPrimeDivisorIndex]);
      int secondPrimeDivisorIndex = GetPrimeFactor(dNum, firstPrimeDivisorIndex
        + 1);
      if (secondPrimeDivisorIndex == -1)
        continue;
      if (DivideDown(dNum, primes[secondPrimeDivisorIndex]) == 1)
        count++;
    }
    return count;
  }

  // start from the index after the previous prime factor's index
  private int GetPrimeFactor(int num, int startIndex=0) {
    if (num == 1)
      return -1;
    // find prime divisor/factor
    for (int i= startIndex; primes[i] <= num && i<primes.Count; i++)
      if (num % primes[i] == 0)
        return i;
    return -1;
  }

  private int DivideDown(int num, int factor) {
    while (num % factor == 0)
      num /= factor;
    return num;
  }

  // Dynamic Programming for generating primes
  // O(N*C)
  /* public void GeneratePrimes()
  {
    primes = new List<int>(new int[] { 2 });
    for (int j = 3; j <= n; j += 2) {
      int pi = 1;   // index inside the prime number collection
      for (; pi < primes.Count; pi++)
        if (j % primes[pi] == 0)
          break;
      if (pi == primes.Count)
        primes.Add(j);
    }
  }*/

  /*
   consider example,
   2, 3, 4,
  */
  // Sieve
  public void GeneratePrimes()
  {
    isPrime = new System.Collections.BitArray(n + 1, true);
    for (int i = 3; i * i <= n; i+=2)
      if (isPrime.Get(i))
        for (int j = i * i; j <= n; j += i)
          isPrime.Set(j, false);

    primes = new List<int>(new int[] { 2 });
    for (int i = 3; i <= n; i+=2)
      if (isPrime.Get(i))
        primes.Add(i);
  }

  public void Input()
  {
    n = int.Parse(Console.ReadLine());
  }
}

public class CF_Solution {
  public static void Main() {
    PrimeUtil primeDemo = new PrimeUtil();
    primeDemo.Input();
    primeDemo.GeneratePrimes();
    Console.WriteLine(primeDemo.FindAlmostPrimes());
  }
}


// done
/***************************************************************************
* Title : Almost Prime
* URL   : http://codeforces.com/problemset/problem/26/A
* Contst: Offline
* Date  : 2018-04-27
* Author: Atiq Rahman
* Comp  : O(N)
* Status: Accepted
* Notes : This is not really a good problem for practicing implementation of
*   doubly linked list. Building LinkedList is not trivial since nodes are out
*   of order.. we can say this place for practicing alternative doubly linked
*   list representation.
*
*   Applications of this problem:
*   Test Prime Number Generatation algorithms
* meta  : tag-linked-list, tag-easy
***************************************************************************/
using System;
using System.Collections.Generic;

public class PrimeUtil {
  // The access level for class members and struct members, including nested
  // classes and structs, is private by default.
  // ref: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/
  // classes-and-structs/access-modifiers
  List<int> primes;
  int n;

  // Divide each candidate number (starting from 6) by prime numbers to find
  // divisors. Keep dividing the number with the divisor/factor. Do it twice
  // and if the number comes down to one after those divisions we got an
  // almost prime
  public int FindAlmostPrimes()
  {
    int count = 0;

    for (int num = 6; num <= n; num++) {
      int firstPrimeDivisorIndex = GetPrimeFactor(num);
      if (firstPrimeDivisorIndex == -1)
        continue;
      // divide the number as long as it is divisible by factor
      int dNum = DivideDown(num, primes[firstPrimeDivisorIndex]);
      int secondPrimeDivisorIndex = GetPrimeFactor(dNum, firstPrimeDivisorIndex
        + 1);
      if (secondPrimeDivisorIndex == -1)
        continue;
      if (DivideDown(dNum, primes[secondPrimeDivisorIndex]) == 1)
        count++;
    }
    return count;
  }

  // start from the index after the previous prime factor's index
  private int GetPrimeFactor(int num, int startIndex=0) {
    if (num == 1)
      return -1;
    // find prime divisotr/factor
    for (int i= startIndex; primes[i] <= num && i<primes.Count; i++)
      if (num % primes[i] == 0)
        return i;
    return -1;
  }

  private int DivideDown(int num, int factor) {
    while (num % factor == 0)
      num /= factor;
    return num;
  }

  // Dynamic Programming for generating primes
  // O(N*C)
  public void GeneratePrimes() {
    primes = new List<int>(new int[] { 2 });
    for (int j = 3; j <= n; j += 2) {
      int pi = 1;   // index inside the prime number collection
      for (; pi < primes.Count; pi++)
        if (j % primes[pi] == 0)
          break;
      if (pi == primes.Count)
        primes.Add(j);
    }
  }

  public void Input()
  {
    n = int.Parse(Console.ReadLine());
  }
}

public class CF_Solution {
  public static void Main() {
    PrimeUtil primeDemo = new PrimeUtil();
    primeDemo.Input();
    primeDemo.GeneratePrimes();
    Console.WriteLine(primeDemo.FindAlmostPrimes());
  }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using static Template;
using static System.Console;
using static System.Convert;
using static System.Math;
using Pi = Pair<int, int>;

class Solver
{
    public void Solve(Scanner sc)
    {
        int N, M;
        sc.Make(out N, out M);
        int[] res = new int[N],ex=new int[N];
        int[] ct = new int[M],ts=new int[M];

        var pq = new PriorityQueue<Pi>((a,b)=>a.v1-b.v1);
        for(var i = 0; i < M; i++)
        {
            int s, t, c;
            sc.Make(out s, out t, out c);
            s--;t--;
            res[t] = M+1;
            ts[i] = t;
            ex[t] = i;
            pq.Push(new Pi(s,i));
            ct[i] = c;
        }
        var f = new PriorityQueue<Pair<int,int,int>>((a, b) => a.v1 - b.v1);
        var use = new bool[M];
        for(var i = 0; i < N; i++)
        {
            while (pq.Any() && pq.Top.v1 == i)
                f.Push(new Pair<int,int,int>(ts[pq.Top.v2], ct[pq.Top.v2],pq.Pop().v2));
            if (res[i] == M+1)
            {
                if (!use[ex[i]]) Fail(-1);
                continue;
            }
            if (!f.Any()) continue;
            var p = f.Pop();
            res[i] = p.v3+1;
            p.v2--;
            if (p.v2 != 0) f.Push(p);
            else use[p.v3] = true;
        }

        Console.WriteLine(string.Join(" ", res));

    }
}

public class PriorityQueue<T>
{
    private List<T> data = new List<T>();
    private Comparison<T> cmp;
    public int Count { get { return data.Count; } }
    public T Top { get { return data[0]; } }
    public PriorityQueue() { cmp = cmp ?? Comparer<T>.Default.Compare; }

    public PriorityQueue(Comparison<T> comparison) { cmp = comparison; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private int Parent(int i)
        => (i - 1) >> 1;
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private int Left(int i)
        => (i << 1) + 1;
    public T Push(T val)
    {
        int i = data.Count;
        data.Add(val);
        while (i > 0)
        {
            int p = Parent(i);
            if (cmp(data[p], val) <= 0)
                break;
            data[i] = data[p];
            i = p;
        }
        data[i] = val;
        return val;
    }
    public T Pop()
    {
        var ret = data[0];
        var p = 0;
        var x = data[data.Count - 1];
        while (Left(p) < data.Count - 1)
        {
            var l = Left(p);
            if (l < data.Count - 2 && cmp(data[l + 1], data[l]) < 0) l++;
            if (cmp(data[l], x) >= 0)
                break;
            data[p] = data[l];
            p = l;
        }
        data[p] = x;
        data.RemoveAt(data.Count - 1);
        return ret;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public bool Any() => data.Count > 0;
}
#region Template
public static class Template
{
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        new Solver().Solve(new Scanner());
        Console.Out.Flush();
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T>
    { if (a.CompareTo(b) == 1) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T>
    { if (a.CompareTo(b) == -1) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b)
    { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static T[] Create<T>(int n, Func<T> f)
    {
        var rt = new T[n];
        for (var i = 0; i < rt.Length; ++i)
            rt[i] = f();
        return rt;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static T[] Create<T>(int n, Func<int, T> f)
    {
        var rt = new T[n];
        for (var i = 0; i < rt.Length; ++i)
            rt[i] = f(i);
        return rt;
    }
    public static T[] Copy<T>(this T[] A)
        => Create(A.Length, i => A[i]);
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}

public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    public Pair<T1, T2> PairMake<T1, T2>() => new Pair<T1, T2>(Next<T1>(), Next<T2>());
    public Pair<T1, T2, T3> PairMake<T1, T2, T3>() => new Pair<T1, T2, T3>(Next<T1>(), Next<T2>(), Next<T3>());
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
}

public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString() => $"{v1.ToString()} {v2.ToString()}";
    public void Tie(out T1 a, out T2 b) { a = v1; b = v2; }
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString() => $"{base.ToString()} {v3.ToString()}";
    public void Tie(out T1 a, out T2 b, out T3 c) { Tie(out a, out b); c = v3; }
}
#endregion


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Petya_Exam
{
    class Program
    {
        struct Exam
        {
            public int ExamIndex;
            public int Publish;
            public int ExamDay;
            public int PrepDays;
        }

        static void Main(string[] args)
        {
            List<Exam> list2 = new List<Exam>();
            int N_Days;
            int Total_exams;

                string[] s = (Console.ReadLine()).Split(' ');
                N_Days = int.Parse(s[0]);
                Total_exams = int.Parse(s[1]);

                for (int i = 0; i < Total_exams; ++i)
                {
                    Exam exm;
                    s = (Console.ReadLine()).Split(' ');
                    exm.ExamIndex = i + 1;
                    exm.Publish = int.Parse(s[0]);
                    exm.ExamDay = int.Parse(s[1]);
                    exm.PrepDays = int.Parse(s[2]);
                    list2.Add(exm);
                }

           list2.Sort((x, y) => x.ExamDay.CompareTo(y.ExamDay));
            List<int> seq = new List<int>();
            for (int i = 0; i <= N_Days; ++i)
            {
                seq.Add(0);
            }
            int print = 0;
            foreach (Exam l in list2)
            {
                if (l.Publish - 1 + l.PrepDays < l.ExamDay)
                {
                    if (Ispossible(l.ExamIndex, l, seq))
                    {
                        seq[l.ExamDay] = Total_exams + 1;

                        continue;
                    }
                    else
                    {
                        print = -1;
                        break;
                    }
                }
                else
                {
                    print = -1;
                    break;
                }
            }
            if (print == 0)
            {
                if (seq.Sum() != 0)
                {
                    for (int j = 1; j < seq.Count; ++j)
                    {
                        if (j + 1 == seq.Count)
                        {
                            Console.Write(seq[j]);
                            continue;
                        }
                        Console.Write(seq[j] + " ");
                    }
                }
                else
                {
                    Console.WriteLine("-1");
                }
            }
            else
            {
                Console.WriteLine("-1");
            }

            //Console.ReadKey();
        }

        private static bool Ispossible(int exam_number, Exam l, List<int> seq)
        {
            int days = l.PrepDays;

            int i = l.Publish;
            while (i < l.ExamDay && days > 0)
            {
                if (seq[i] == 0)
                {
                    seq[i] = exam_number;
                    days--;
                }
                i++;
            }
            return days == 0 ? true : false;
        }

    }
}


using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace CodeForces.PRACTICE
{
    // Kyoya and Photobooks (brute force, math)
    class _554A
    {
        static void Main(string[] args)
        {
            string s = Console.ReadLine();

            // egyik megoldas:
            //Console.WriteLine((s.Length + 1) * 25 + 1);

            HashSet<string> set = new HashSet<string>();

            int n = s.Length;
            for (int i = 0; i <= n; i++)
                for (char j = 'a'; j <= 'z'; j++)
                {
                    string t = s.Substring(0, i) + j + s.Substring(i);
                    set.Add(t);
                }
            Console.WriteLine(set.Count);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class PairVariable : IComparable<PairVariable>
{
    public int a, b;
    public PairVariable()
    {
        a = b = 0;
    }
    public PairVariable(string s)
    {
        string[] q = s.Split();
        a = int.Parse(q[0]);
        b = int.Parse(q[1]);
    }
    public PairVariable(int a, int b)
    {
        this.a = a;
        this.b = b;
    }
    public int CompareTo(PairVariable pv)
    {
        if (this.a > pv.a)
        {
            return 1;
        }
        else if (this.a < pv.a)
        {
            return -1;
        }
        else
        {
            if (this.b >= pv.b)
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }
    }

}
namespace ConsoleApplication2
{

    class Program
    {

        static int[,] matrix;
        static int[] mark;

        static void DFS(int v)
        {

            mark[v] = 1;
            for (int i = 0; i < matrix.GetLength(0); i++)
            {

                if (matrix[v, i] == 1)
                {

                    if (mark[v] == 0)
                    {
                        DFS(i);
                    }
                }
            }

        }
        static bool IsPrime(int n)
        {
            for (int i = 2; i <= Math.Sqrt(n); i++)
            {
                if (n % i == 0)
                {
                    return false;
                }
            }
            return true;
        }
        static void IsYesNo(bool b)
        {
            if (b)
            {
                Console.WriteLine("YES");
            }
            else
            {
                Console.WriteLine("NO");
            }
        }
        static void Main(string[] args)
        {
            //string[] ss = Console.ReadLine().Split();
            string s = Console.ReadLine();
            Console.WriteLine(1+((s.Length+1)*25));

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] s = new string[3];
            for (int i = 0; i < 3;i++)
            {
                s[i] = Console.ReadLine();
            }
            SolveProblem(s);
            Console.ReadLine();

        }

        static void SolveProblem(string [] s)
        {
            Dictionary<char, int> coins = new Dictionary<char, int>();
            coins.Add('A',0);
            coins.Add('B', 0);
            coins.Add('C', 0);

            for (int i = 0; i < s.Length;i++)
            {
                switch (s [i] [1])
                {
                    case '>':
                        coins[s[i][0]] += 1;
                        break;
                    case '<':
                        coins[s[i][2]] += 1;
                        break;

                }
            }

            if (coins ['A'] == coins ['B'] && coins['B'] == coins['C'])
            {
                Console.WriteLine("Impossible");

            } else
            {
                var items = from pair in coins
                            orderby pair.Value ascending
                            select pair;
                foreach (KeyValuePair <char, int> pair in items)
                {
                    Console.Write(pair.Key);
                }
            }
        }

    }

}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;
using System.Linq;
using System.Threading;

class Program
{

    void solve()
    {

        string[] s = new string[3];
        for (int i = 0; i < 3; i++)
            s[i] = nextString();
        string all = "ABC";
        foreach (char c1 in all)
            foreach (char c2 in all)
                if (c1 != c2)
                    foreach (char c3 in all)
                        if (c3 != c1 && c3 != c2)
                        {
                            bool ok = true;
                            string cur = "" + c1 + c2 + c3;
                            for (int i = 0; i < 3; i++)
                            {
                                int i1 = cur.IndexOf(s[i][0]);
                                int i2 = cur.IndexOf(s[i][2]);
                                if (s[i][1] == '<')
                                {
                                    if (i1 > i2)
                                        ok = false;
                                }
                                if (s[i][1] == '>')
                                {
                                    if (i1 < i2)
                                        ok = false;
                                }
                            }
                            if (ok)
                            {
                                println(cur);
                                return;
                            }

                        }
        println("Impossible");
    }

    ////////////
    private void println(int[] ar)
    {
        for (int i = 0; i < ar.Length; i++)
        {
            if (i == ar.Length - 1)
                println(ar[i]);
            else
                print(ar[i] + " ");
        }
    }
    private void println(int[] ar, bool add)
    {
        int A = 0;
        if (add)
            A++;
        for (int i = 0; i < ar.Length; i++)
        {
            if (i == ar.Length - 1)
                println(ar[i] + A);
            else
                print((ar[i] + A) + " ");
        }
    }

    private void println(string Stringst)
    {
        Console.WriteLine(Stringst);
    }
    private void println(char charnum)
    {
        Console.WriteLine(charnum);
    }
    private void println(int Intnum)
    {
        Console.WriteLine(Intnum);
    }
    private void println(long Longnum)
    {
        Console.WriteLine(Longnum);
    }
    private void println(double Doublenum)
    {
        string s = Doublenum.ToString(CultureInfo.InvariantCulture);
        Console.WriteLine(s);
    }

    private void print(string Stringst)
    {
        Console.Write(Stringst);
    }
    private void print(int Intnum)
    {
        Console.Write(Intnum);
    }
    private void print(char charnum)
    {
        Console.Write(charnum);
    }
    private void print(long Longnum)
    {
        Console.Write(Longnum);
    }
    private void print(double Doublenum)
    {
        Console.Write(Doublenum);
    }

    string[] inputLine = new string[0];
    int inputInd = 0;
    string nextLine()
    {
        return Console.ReadLine();
    }
    void readInput()
    {
        if (inputInd != inputLine.Length)
            throw new Exception();
        inputInd = 0;
        inputLine = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (inputLine.Length == 0)
            readInput();

    }
    int nextInt()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return int.Parse(inputLine[inputInd++]);
    }
    long nextLong()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return long.Parse(inputLine[inputInd++]);
    }
    double nextDouble()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return double.Parse(inputLine[inputInd++]);
    }
    string nextString()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return inputLine[inputInd++];
    }
    static void Main(string[] args)
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        new Program().solve();
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace CodeForces
{
    static class Program
    {
        static void Main()
        {
            const string filePath = @"Data\R468A.txt";
            if (System.IO.File.Exists(filePath))
            {
                Console.SetIn(new System.IO.StreamReader(filePath));
            }

            IProblem counter = new R468A();

            foreach (var result in counter.GetResults())
            {
                Console.WriteLine(result);
            }
        }
    }

    internal class R468A : ProblemBase
    {
        public override IEnumerable<string> GetResults()
        {
            var a = this.ReadInt32();
            var b = this.ReadInt32();
            var delta = Math.Abs(b - a);
            var s1 = delta / 2;
            var s2 = delta / 2;
            if (delta % 2 == 1)
            {
                s2++;
            }

            yield return ((s1+1)*s1/2+ (s2 + 1) * s2 / 2).ToString();
        }
    }

    internal class R468B : ProblemBase
    {
        public override IEnumerable<string> GetResults()
        {
            yield return "n/a";
        }
    }

    internal class R468C : ProblemBase
    {
        public override IEnumerable<string> GetResults()
        {
            yield return "n/a";
        }
    }

    internal class R468D : ProblemBase
    {
        public override IEnumerable<string> GetResults()
        {
            yield return "n/a";
        }
    }

    abstract class MultipleTestsBase : ProblemBase
    {
        public sealed override IEnumerable<string> GetResults()
        {
            var t = Convert.ToInt32(Console.ReadLine());
            for (int testCaseNumber = 0; testCaseNumber < t; testCaseNumber++)
            {
                foreach (var result in GetTestResult(testCaseNumber + 1))
                {
                    yield return result;
                }

            }

        }

        protected abstract IEnumerable<string> GetTestResult(int caseNumber);
    }

    public interface IProblem
    {
        IEnumerable<string> GetResults();
    }

    public abstract class ProblemBase : IProblem
    {
        /// <summary>
        /// Pring array of T
        /// </summary>
        /// <typeparam name="T">Generic paramter.</typeparam>
        /// <param name="items">The items.</param>
        /// <param name="prefixMessage">The message shown first.</param>
        public void PrintArray<T>(IEnumerable<T> items, string prefixMessage)
        {
            Console.WriteLine("{0}: {1}", prefixMessage, string.Join(",", items));
        }

        public void WriteDiagnostics(string message, params object[] objects)
        {
            Console.WriteLine(message, objects);
        }

        public virtual IEnumerable<string> GetResults()
        {
            yield return "No result";
        }

        protected int[] ReadIntArray()
        {
            return Array.ConvertAll(ReadTokens(), Convert.ToInt32);
        }

        protected string[] ReadTokens()
        {
            var readLine = Console.ReadLine();
            if (readLine == null)
            {
                throw new Exception("Value read from Console is null");
            }
            return readLine.Split(' ');
        }

        protected int ReadInt32()
        {
            return Convert.ToInt32(Console.ReadLine());
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = int.Parse(Console.ReadLine());
            int b = int.Parse(Console.ReadLine());
            int c = Math.Abs(a - b);
            int d = c / 2;
            int e = c - d;
            int f = (1 + d) * d / 2;
            int g = (1 + e) * e / 2;
            int h = f + g;
            Console.WriteLine(h);
            //Console.ReadKey();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace SecTry_1040AF
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<int> container = Console.ReadLine().Split().Select(int.Parse);
            int n = container.ElementAt(0), whiteCost = container.ElementAt(1), blackCost = container.ElementAt(2), ans = 0;
            List<int> line = Console.ReadLine().Split().Select(int.Parse).ToList();

            for (int i = 0, j = line.Count - 1; i <= j; i++, j--)
            {
                if (i == j && line[i] == 2) ans += Math.Min(whiteCost, blackCost);
                else if (line[i] != 2 && line[j] == 2) ans += line[i] == 0 ? whiteCost : blackCost;
                else if (line[i] == 2 && line[j] != 2) ans += line[j] == 0 ? whiteCost : blackCost;
                else if (line[i] == 2 && line[j] == 2) ans += Math.Min(blackCost, whiteCost)*2;
                else if (line[i] != line[j])
                {
                    ans = -1;
                    break;
                }

            }

            Console.WriteLine(ans);

        }
    }
}


using System;
using System.Linq;

namespace codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nm = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
            int[] a = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
            int sum = 0;
            for (int i = 0; i < nm[0] / 2; i++)
            {
                if (a[i] != 2 && a[nm[0] - 1 - i] != 2 && a[i] != a[nm[0] - 1 - i])
                {
                    Console.WriteLine(-1);
                    return;
                }
                if (a[i] == a[nm[0] - 1 - i] && a[i] != 2)
                    continue;
                if (a[i] == a[nm[0] - 1 - i] && a[i] == 2)
                    sum += Math.Min(nm[1], nm[2]) * 2;
                else if (a[i] == 2 && a[nm[0] - 1 - i] == 0 || a[i] == 0 && a[nm[0] - 1 - i] == 2)
                    sum += nm[1];
                else sum += nm[2];
            }
            if (nm[0] % 2!=0)
                sum += a[nm[0]/2] == 2 ? Math.Min(nm[1], nm[2]) : 0;
            Console.WriteLine(sum);
        }
    }
}


using System;
using System.Linq;
using CompLib.Util;
using System.Threading;
using CompLib.Mathematics;

public class Program
{
    private int N;

    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();

        /*
         * 街0 ~ n+1
         *
         * 1/2の確率で 1~nに建てる
         *
         * iにパワーpの建てる
         * 距離p未満の街に届く
         *
         * 0とn+1に届かない
         * 1~nには1つから届く
         *
         *
         */

        // i未満の街に届く
        // iには届いてない
        // 確率
        ModInt[] dp = new ModInt[N + 2];
        dp[1] = 1;

        ModInt odd = 1;
        ModInt even = 0;

        ModInt h = ModInt.Inverse(2);

        for (int i = 2; i <= N + 1; i++)
        {
            odd *= h;
            even *= h;
            if (i % 2 == 0)
            {
                dp[i] = odd;
                even += odd;
            }
            else
            {
                dp[i] = even;
                odd += even;
            }
        }

        Console.WriteLine(dp[N + 1]);
    }

    public static void Main(string[] args) => new Program().Solve();
    // public static void Main(string[] args) => new Thread(new Program().Solve, 1 << 27).Start();
}

// https://bitbucket.org/camypaper/complib
namespace CompLib.Mathematics
{
    #region ModInt

    /// <summary>
    /// [0,<see cref="Mod"/>) までの値を取るような数
    /// </summary>
    public struct ModInt
    {
        /// <summary>
        /// 剰余を取る値．
        /// </summary>
        // public const long Mod = (int) 1e9 + 7;
        public const long Mod = 998244353;

        /// <summary>
        /// 実際の数値．
        /// </summary>
        public long num;

        /// <summary>
        /// 値が <paramref name="n"/> であるようなインスタンスを構築します．
        /// </summary>
        /// <param name="n">インスタンスが持つ値</param>
        /// <remarks>パフォーマンスの問題上，コンストラクタ内では剰余を取りません．そのため，<paramref name="n"/> ∈ [0,<see cref="Mod"/>) を満たすような <paramref name="n"/> を渡してください．このコンストラクタは O(1) で実行されます．</remarks>
        public ModInt(long n)
        {
            num = n;
        }

        /// <summary>
        /// このインスタンスの数値を文字列に変換します．
        /// </summary>
        /// <returns>[0,<see cref="Mod"/>) の範囲内の整数を 10 進表記したもの．</returns>
        public override string ToString()
        {
            return num.ToString();
        }

        public static ModInt operator +(ModInt l, ModInt r)
        {
            l.num += r.num;
            if (l.num >= Mod) l.num -= Mod;
            return l;
        }

        public static ModInt operator -(ModInt l, ModInt r)
        {
            l.num -= r.num;
            if (l.num < 0) l.num += Mod;
            return l;
        }

        public static ModInt operator *(ModInt l, ModInt r)
        {
            return new ModInt(l.num * r.num % Mod);
        }

        public static implicit operator ModInt(long n)
        {
            n %= Mod;
            if (n < 0) n += Mod;
            return new ModInt(n);
        }

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(ModInt v, long k)
        {
            return Pow(v.num, k);
        }

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(long v, long k)
        {
            long ret = 1;
            for (k %= Mod - 1; k > 0; k >>= 1, v = v * v % Mod)
                if ((k & 1) == 1)
                    ret = ret * v % Mod;
            return new ModInt(ret);
        }

        /// <summary>
        /// 与えられた数の逆元を計算します．
        /// </summary>
        /// <param name="v">逆元を取る対象となる数</param>
        /// <returns>逆元となるような値</returns>
        /// <remarks>法が素数であることを仮定して，フェルマーの小定理に従って逆元を O(log N) で計算します．</remarks>
        public static ModInt Inverse(ModInt v)
        {
            return Pow(v, Mod - 2);
        }
    }

    #endregion

    #region Binomial Coefficient

    public class BinomialCoefficient
    {
        public ModInt[] fact, ifact;

        public BinomialCoefficient(int n)
        {
            fact = new ModInt[n + 1];
            ifact = new ModInt[n + 1];
            fact[0] = 1;
            for (int i = 1; i <= n; i++)
                fact[i] = fact[i - 1] * i;
            ifact[n] = ModInt.Inverse(fact[n]);
            for (int i = n - 1; i >= 0; i--)
                ifact[i] = ifact[i + 1] * (i + 1);
            ifact[0] = ifact[1];
        }

        public ModInt this[int n, int r]
        {
            get
            {
                if (n < 0 || n >= fact.Length || r < 0 || r > n) return 0;
                return fact[n] * ifact[n - r] * ifact[r];
            }
        }

        public ModInt RepeatedCombination(int n, int k)
        {
            if (k == 0) return 1;
            return this[n + k - 1, k];
        }
    }

    #endregion
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            if (_index >= _line.Length)
            {
                string s;
                do
                {
                    s = Console.ReadLine();
                } while (s.Length == 0);

                _line = s.Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public string ReadLine()
        {
            _index = _line.Length;
            return Console.ReadLine();
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            string s = Console.ReadLine();
            _line = s.Length == 0 ? new string[0] : s.Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;
using static System.Math;

namespace AtTest.CodeForces._1452
{
    class D
    {
        static void Main(string[] args)
        {
            var sw = new System.IO.StreamWriter(OpenStandardOutput()) { AutoFlush = false };
            SetOut(sw);

            Method(args);

            Out.Flush();
        }

        static void Method(string[] args)
        {
            int n = ReadInt();
            long mask = 998244353;

            long[] dp = new long[n+1];
            dp[0] = 1;
            dp[1] = 1;
            long[] oddSums = new long[n + 1];
            oddSums[1] = 1;
            long[] evenSums = new long[n + 1];
            evenSums[0] = 1;

            for(int i = 2; i <= n; i++)
            {
                if (i % 2 == 1)
                {
                    dp[i] = evenSums[i - 1];
                    dp[i] %= mask;
                    oddSums[i] = oddSums[i - 2] + dp[i];
                    oddSums[i] %= mask;
                }
                else
                {
                    dp[i] = oddSums[i - 1];
                    dp[i] %= mask;
                    evenSums[i] = evenSums[i - 2] + dp[i];
                    evenSums[i] %= mask;
                }
            }

            long div = 1;
            for(int i = 0; i < n; i++)
            {
                div *= 2;
                div %= mask;
            }

            long res = dp[n];
            res *= Inverse(div, mask);
            res %= mask;
            WriteLine(res);
        }

        static long Inverse(long val,long mask)
        {
            long a = mask;
            long b = val % mask;
            long x = 1;
            long x1 = 0;
            long y = 0;
            long y1 = 1;
            while (b > 0)
            {
                long q = a / b;
                long r = a % b;
                long x2 = (mask + x - (q * x1) % mask) % mask;
                long y2 = (mask + y - (q * y1) % mask) % mask;
                a = b;
                b = r;
                x = x1;
                x1 = x2;
                y = y1;
                y1 = y2;
            }
            return y;
        }

        private static string Read() { return ReadLine(); }
        private static char[] ReadChars() { return Array.ConvertAll(Read().Split(), a => a[0]); }
        private static int ReadInt() { return int.Parse(Read()); }
        private static long ReadLong() { return long.Parse(Read()); }
        private static double ReadDouble() { return double.Parse(Read()); }
        private static int[] ReadInts() { return Array.ConvertAll(Read().Split(), int.Parse); }
        private static long[] ReadLongs() { return Array.ConvertAll(Read().Split(), long.Parse); }
        private static double[] ReadDoubles() { return Array.ConvertAll(Read().Split(), double.Parse); }
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, m;
            double q;

            n = int.Parse(Console.ReadLine());
            m = 8 * n + 1;
            q = Math.Sqrt(m);
            if (Math.Truncate(q) == q) Console.WriteLine("YES");
            else Console.WriteLine("NO");
        }
    }
}


using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            var s = 2*Convert.ToInt16(Console.ReadLine());
            var a = (byte) Math.Sqrt(s);
            Console.WriteLine(a*(a+1)==s?"YES":"NO");
        }
    }
}


using System;
using System.IO;
using System.Text;

namespace MUH_and_House_of_Cards
{
    internal class Program
    {
        private static readonly StreamReader reader = new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);
        private static readonly StreamWriter writer = new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            long n = long.Parse(reader.ReadLine());

            if (n < 2)
            {
                writer.WriteLine("0");
            }
            else
            {
                long count = 2;
                long delta = 2;
                int flour = 0;
                while (count <= n)
                {
                    flour++;
                    delta += 3;
                    count += delta;
                }

                if (flour%3 == 2)
                {
                    if (n%3 == 0)
                        flour -= 2;
                    else
                    {
                        flour++;
                    }
                }
                else if (flour%3 == 1)
                {
                    if (n%3 == 2)
                        flour += 2;
                    else
                    {
                        flour--;
                    }
                }

                writer.WriteLine(flour/3);
            }

            writer.Flush();
        }
    }
}