using System;

namespace CSharp
{
    public class _991A
    {
        public static void Main()
        {
            string[] tokens = Console.ReadLine().Split();

            int a = int.Parse(tokens[0]);
            int b = int.Parse(tokens[1]);
            int c = int.Parse(tokens[2]);
            int n = int.Parse(tokens[3]);

            if (a + b - c > n | c > a || c > b)
            {
                Console.WriteLine(-1);
            }
            else
            {
                int failed = n - a - b + c;
                Console.WriteLine(failed <= 0 ? -1 : failed);
            }
        }
    }
}


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

namespace Escape
{
    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)
        {
            int vp = Next(), vd = Next(), t = Next(), f = Next(), c = Next();

            t *= vp*vd;
            f *= vp * vd;
            c *= vp * vd;

            int count = 0;
            int p = 0;
            int d = 0;
            int ds = 0;
            int towait = t;
            while (true)
            {
                p += vp;

                if (ds == 0)
                {
                    towait--;
                    if (towait < 0)
                    {
                        ds = 1;
                        d += vd;
                    }
                }
                else if (ds == 1)
                {
                    d += vd;
                }
                else
                {
                    d -= vd;
                }

                if (d >= p)
                {
                    if (d==p &&p==c)
                        break;
                    count++;
                    ds = 2;
                    d = p - (d - p);
                }

                if (ds == 2 && d <= 0)
                {
                    d = -d;
                    ds = 0;
                    towait = f;
                }

                if (p >= c)
                {
                    break;
                }
            }

            writer.WriteLine(count);
            writer.Flush();
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


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

namespace CF105D2B
{
    class CF105D2B
    {
        public static void Main(string[] args)
        {
            EasyScanner sc = new EasyScanner(Console.In);
            double vp = sc.NextInt();
            double vd = sc.NextInt();
            double t = sc.NextInt();
            double f = sc.NextInt();
            double c = sc.NextInt();

            if (vp >= vd)
            {
                Console.Out.WriteLine(0);
                return;
            }

            double x = vp * t;
            x += vp * (x / (vd - vp));

            int count = 0;
            while (x < c)
            {
                count++;
                x += vp * (x / vd);
                x += vp * f;
                x += vp * (x / (vd - vp));
            }
            Console.Out.WriteLine(count);
        }
    }

    class EasyScanner
    {
        private TextReader reader;
        private Queue<string> tokens;

        public EasyScanner(TextReader reader)
        {
            this.reader = reader;
            this.tokens = new Queue<string>();
        }

        private void MaybeReadLine()
        {
            if (tokens.Count > 0)
            {
                return;
            }
            string line = reader.ReadLine();
            foreach (string token in line.Split())
            {
                tokens.Enqueue(token);
            }
        }

        public int NextInt()
        {
            MaybeReadLine();
            string token = tokens.Dequeue();
            return int.Parse(token);
        }

        public long NextLong()
        {
            MaybeReadLine();
            string token = tokens.Dequeue();
            return long.Parse(token);
        }

        public double NextDouble()
        {
            MaybeReadLine();
            string token = tokens.Dequeue();
            return double.Parse(token);
        }

        public string NextString()
        {
            MaybeReadLine();
            string token = tokens.Dequeue();
            return token;
        }
    }
}


using System;

public class Program
{
	public static void Main()
	{
		string input = Console.ReadLine();
		string normalized = "";
		int count = 0;
		foreach(var item in input)
		{
			if(item != '/')
			{
				normalized += item.ToString();
				count = 0;
			}
			else if(count == 0)
			{
				normalized += item.ToString();
				count++;
			}
		}

		string result = normalized;
		if(normalized.Length > 1 && normalized[normalized.Length - 1] == '/')
		{
			result = normalized.Substring(0, normalized.Length - 1);
		}

		Console.WriteLine(result);
	}
}


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

namespace CodeForces
{
    static class Reader
    {
        public static int NextInt()
        {
            int ret = 0;
            char c;

            while (!char.IsDigit(c = (char)Console.Read()))
            {
                if (c == '-')
                    return -NextInt();
            }
            do
            {
                ret = ret * 10 + c - '0';
            } while (char.IsDigit(c = (char)Console.Read()));

            return ret;
        }

        public static double NextDouble()
        {
            double ret = 0;
            char c;

            while (!char.IsDigit(c = (char)Console.Read()))
            {
                if (c == '-')
                    return -NextDouble();
            }
            do
            {
                ret = ret * 10 + c - '0';
            } while (char.IsDigit(c = (char)Console.Read()));
            if (c != '.') return ret;

            double p10 = 0.1;
            while (char.IsDigit(c = (char)Console.Read()))
            {
                ret += p10 * (c - '0');
                p10 *= 0.1;
            }

            return ret;
        }

        public static string NextToken()
        {
            StringBuilder ret = new StringBuilder();
            char c;

            while (char.IsWhiteSpace(c = (char)Console.Read())) ;
            do
            {
                ret.Append(c);
            } while (!char.IsWhiteSpace(c = (char)Console.Read()));

            return ret.ToString();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string s = Reader.NextToken();
            while (s != s.Replace("//", "/"))
                s = s.Replace("//", "/");
            if (s.Length > 1 && s.EndsWith("/"))
                s = s.Substring(0, s.Length - 1);
            Console.WriteLine(s);
        }
    }
}


using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
class Program{
	static void Main() {
		int[] a = Console.ReadLine().Split().Select(int.Parse).ToArray();
		int[] b = Console.ReadLine().Split().Select(int.Parse).ToArray();
		int[] c = Console.ReadLine().Split().Select(int.Parse).ToArray();
		long[] v1 = new long[2]{b[0] - a[0], b[1] - a[1]};
		long[] v2 = new long[2]{c[0] - b[0], c[1] - b[1]};
		long product = (v1[0] * v2[1]) - (v1[1] * v2[0]);

		if(product == 0)
			Console.WriteLine("TOWARDS");
		else if(product > 0)
			Console.WriteLine("LEFT");
		else
			Console.WriteLine("RIGHT");
	}
}


using System;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main()
        {
            string[] a = Console.ReadLine().Split(' '),
                     b = Console.ReadLine().Split(' '),
                     c = Console.ReadLine().Split(' ');
            string k = Solver(Int32.Parse(a[0]), Int32.Parse(a[1]), Int32.Parse(b[0]),
                              Int32.Parse(b[1]), Int32.Parse(c[0]), Int32.Parse(c[1]));
            Console.WriteLine(k);
        }

        public static string Solver(int ax, int ay, int bx, int by, int cx, int cy)
        {

            Int64[,] mat = new Int64[3, 3] { { 1, 1, 1 }, { bx - ax, by - ay, 0 }, { cx - bx, cy - by, 0 } };
            Int64 k = mat[1, 0] * mat[2, 1] - mat[1, 1] * mat[2, 0];
            if (k > 0) return "LEFT";
            if (k < 0) return "RIGHT";
            return "TOWARDS";

        }
    }
}


using System;

namespace _887B
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            n = int.Parse(Console.ReadLine());
            int[,] array = new int[n, 6];
            for (int i = 0; i < n; i++)
            {
                //Console.Clear();
                string inputDice = Console.ReadLine();
                string[] splitInputDice =  inputDice.Split(' ');

                for (int j = 0; j < 6; j++)
                {
                    array[i, j] = int.Parse(splitInputDice[j]);
                }
            }

            int[] checker = new int[1000];
            Array.Clear(checker, 0, checker.Length);

            for (int i = 0; i < n; i++)
            {
                for(int j = 0; j < 6; j++)
                {
                    checker[array[i, j]] = 1;

                    for(int k = 0; k < n; k++ )
                    {
                        if (k == i) continue;
                        for(int l = 0; l < 6; l++)
                        {
                            int index = array[i, j] * 10 + array[k, l];
                            checker[index] = 1;
                            for(int m = 0; m < n; m++)
                            {
                                if (m == i || m == k) continue;
                                for(int o = 0; o < 6; o++)
                                {
                                    int index2 = array[i, j] * 100 + array[k, l] * 10 + array[m, o];
                                    checker[index2] = 1;
                                }
                            }
                        }
                    }
                }
            }

            int res = 0;
            for(int i = 1; i < 1000; i++)
            {
                if(checker[i] == 0)
                {
                    res = i - 1;
                    break;
                }
            }

            Console.Write(res);

        }
    }
}


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

namespace ConsoleApp14
{
    class Program
    {
        static void Main(string[] args)
        {
            int num2 = 0;
            int n = int.Parse(Console.ReadLine());
            int[][] toks = new int[3][];

            for(int i = 0; i < n; i++)
            {
                int[] temp = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
                toks[i] = temp;
            }

            int number = 0;
            for(int x = 0; x <= 10000; x++)
            {
                number++;
                string tofind = number.ToString();
                int num1 = int.Parse(tofind[0].ToString());
                if (tofind.Length == 2)
                {
                    num2 = int.Parse(tofind[1].ToString());
                }
                bool naid = false;
                for(int i = 0; i < n; i++)
                {
                    if(toks[i].Contains(num1))
                    {
                        naid = true;
                        if(tofind.Length == 1)
                        {
                            break;
                        }
                        else
                        {
                            naid = false;
                            for(int j = 0; j < n; j++)
                            {
                                if (j == i)
                                    continue;
                                if(toks[j].Contains(num2))
                                {
                                    naid = true;
                                    i = n;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (naid == false)
                    break;

            }
            Console.WriteLine(--number);
            Console.ReadLine();
        }
    }
}


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

namespace Divisibility_by_25
{
    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)
        {
            writer.WriteLine(Solve(args));
            writer.Flush();
        }

        private static int Solve(string[] args)
        {
            string s = reader.ReadLine();

            int min = Math.Min(Math.Min(Check(s, '0', '0'), Check(s, '2', '5')), Math.Min(Check(s, '5', '0'), Check(s, '7', '5')));
            if (min == int.MaxValue)
                return -1;

            return min;
        }

        private static int Check(string s, char c1, char c2)
        {
            int index = s.LastIndexOf(c2);
            if (index < 0)
                return int.MaxValue;
            int ans = s.Length - index - 1;
            int index2;
            if (c1 == c2)
                index2 = s.Substring(0, index).LastIndexOf(c1);
            else
                index2 = s.LastIndexOf(c1);

            if (index2 < 0)
                return int.MaxValue;

            if (index2 > index)
                ans += s.Length - index2 - 1;
            else
                ans += s.Length - index2 - 2;

            var b = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                if (i == index || i == index2)
                    continue;
                b.Append(s[i]);
            }

            bool f = b.Length == 0;
            for (int i = 0; i < b.Length; i++)
            {
                if (b[i] != '0')
                {
                    f = true;
                    break;
                }
                ans++;
            }

            if (f)
                return ans;

            return int.MaxValue;
        }
    }
}


using System;
using System.Linq;
using CompLib.Collections;
using CompLib.Util;

public class Program
{

    public void Solve()
    {
        var sc = new Scanner();
        var n = sc.Next().Reverse().ToArray();
        if (n.Length == 1)
        {
            Console.WriteLine("-1");
            return;
        }

        // 先頭0以外
        // 下2桁 00 25 50 75

        int ans = int.MaxValue;

        // 先頭
        for (int i = 0; i < n.Length; i++)
        {
            if (n[i] == '0') continue;
            // 2桁目
            for (int j = 0; j < n.Length; j++)
            {
                if (n.Length > 2 && i == j) continue;
                for (int k = 0; k < n.Length; k++)
                {
                    if (i == k || j == k) continue;

                    bool zero = n[j] == '0' && n[k] == '0';
                    bool twentyfive = n[j] == '2' && n[k] == '5';
                    bool fifty = n[j] == '5' && n[k] == '0';
                    bool seventyfive = n[j] == '7' && n[k] == '5';
                    if (!zero && !twentyfive && !fifty && !seventyfive) continue;
                    var array = new int[n.Length];
                    for (int l = 0; l < n.Length; l++)
                    {
                        if (l == i) array[l] = 0;
                        else if (l == j) array[l] = 2;
                        else if (l == k) array[l] = 3;
                        else array[l] = 1;
                    }
                    int tmp = 0;
                    var bit = new FenwickTree(4);
                    for (int l = 0; l < n.Length; l++)
                    {
                        tmp += bit.Sum(array[l]);
                        bit.Add(array[l], 1);
                    }
                    ans = Math.Min(ans, tmp);
                }
            }
        }
        if (ans == int.MaxValue) Console.WriteLine("-1");
        else Console.WriteLine(ans);
    }

    public static void Main(string[] args) => new Program().Solve();
}

namespace CompLib.Collections
{
    using Num = System.Int32;

    public class FenwickTree
    {
        private readonly Num[] _array;
        public readonly int Count;

        public FenwickTree(int size)
        {
            _array = new Num[size + 1];
            Count = size;
        }

        /// <summary>
        /// A[i]にnを加算
        /// </summary>
        /// <param name="i"></param>
        /// <param name="n"></param>
        public void Add(int i, Num n)
        {
            i++;
            for (; i <= Count; i += i & -i)
            {
                _array[i] += n;
            }
        }

        /// <summary>
        /// [0,r)の和を求める
        /// </summary>
        /// <param name="r"></param>
        /// <returns></returns>
        public Num Sum(int r)
        {
            Num result = 0;
            for (; r > 0; r -= r & -r)
            {
                result += _array[r];
            }

            return result;
        }

        // [l,r)の和を求める
        public Num Sum(int l, int r) => Sum(r) - Sum(l);
    }
}

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()
        {
            while (_index >= _line.Length)
            {
                _line = Console.ReadLine().Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        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()
        {
            _line = Console.ReadLine().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;

namespace _535A
{
    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            string[] translate1 = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
                                     "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
                                 "eighteen", "nineteen"};
            string[] translate2 = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
            if (n <= 19) Console.WriteLine(translate1[n]);
            else if (n % 10 == 0) { Console.WriteLine(translate2[n/10]); }
            else { Console.WriteLine(translate2[n/10]+"-"+translate1[n%10]); }

        }
    }
}


using System;

namespace _535A
{
    class Program
    {
        static string[] zeroToNine = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
        static string[] tenToNineteen = new[] { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        static string[] decades = new[] { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
        static void Main(string[] args)
        {
            int s = int.Parse(Console.ReadLine());
            string result;
            if (s < 10)
                result = zeroToNine[s];
            else if (s >= 10 && s < 20)
                result = tenToNineteen[s - 10];
            else
            {
                result = decades[s / 10 - 2];
                if (s % 10 > 0)
                    result += '-' + zeroToNine[s % 10];
            }
            Console.WriteLine(result);
        }
    }
}


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

namespace Codeforces
{
	class Program
	{
		static void Main(string[] args)
		{
			int x2 = int.Parse(Console.ReadLine());
			int px2 = maxPrimeDivs(x2);
			int min = x2;
			int start2 = ((x2 / px2) - 1) * px2 + 1;

			for (int x1 = start2; x1 <= x2; x1++)
			{
				int px1 = maxPrimeDivs(x1);
				int start1 = ((x1 / px1) - 1) * px1 + 1;
				if (start1 > 2 && start1 < min)
				{
					min = start1;
				}
			}
			Console.WriteLine(min);
			Console.ReadLine();
		}

		private static int maxPrimeDivs(int n)
		{
			int d = 2;
			int result = 0;

			while (d * d <= n)
			{
				if (n % d == 0)
				{
					n /= d;
					if (result < d)
						result = d;
				}
				else d++;
			}
			return Math.Max(result, n);
		}

	}
}


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

namespace Primal_Sport
{
    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)
        {
            writer.WriteLine(Solve(args));
            writer.Flush();
        }

        private static int Solve(string[] args)
        {
            int n = Next();

            var nn = new int[n + 1];
            for (int i = 2; i < nn.Length; i++)
            {
                if (nn[i] == 0)
                {
                    for (int j = i; j < nn.Length; j += i)
                    {
                        nn[j] = i;
                    }
                }
            }

            int min = n;
            for (int j = n - nn[n] + 1; j <= n; j++)
            {
                if (nn[j] != j)
                {
                    min = Math.Min(min, j - nn[j] + 1);
                }
            }

            return min;
        }

        private static int Next()
        {
            int c;
            int res = 0;
            do
            {
                c = reader.Read();
                if (c == -1)
                    return res;
            } while (c < '0' || c > '9');
            res = c - '0';
            while (true)
            {
                c = reader.Read();
                if (c < '0' || c > '9')
                    return res;
                res *= 10;
                res += c - '0';
            }
        }
    }
}


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

namespace Кратные
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] str;
            str = Console.ReadLine().Split(' ');
            int y=Convert.ToInt32(str[0]), b=Convert.ToInt32(str[1]), r=Convert.ToInt32(str[2]), max=y;
            max = Math.Min(max, b - 1);
            max = Math.Min(max, r - 2);

                Console.WriteLine(3*max+3);

                //     Console.ReadKey();

        }
    }
}


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[]y=Console.ReadLine().Split(' ');
            int[]a=new int[3];
            a[0]=1;
            a[1]=2;
            a[2]=3;
            int sum=0;
            while(true)
            {
                 if((a[0]>=int.Parse(y[0]))||(a[1]>=int.Parse(y[1]))||(a[2]>=int.Parse(y[2])))
                 {
                      sum=a[0]+a[1]+a[2];
                      break;
                 }
                 else
                 {
                 a[0]++;
                 a[1]++;
                 a[2]++;
            }
            }
            Console.WriteLine(sum);

        }
    }
}


using System;
using System.Linq;

namespace Task_C
{
    class Program
    {
        private static int CardIndex(string card)
        {
            var num = card[1] - '1';
            int color = 0;
            if (card[0] == 'R')
                color = 0;
            if (card[0] == 'G')
                color = 1;
            if (card[0] == 'B')
                color = 2;
            if (card[0] == 'Y')
                color = 3;
            if (card[0] == 'W')
                color = 4;

            var index = (1 << num) | (1 << (color + 5));
            return index;
        }

        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            var cards = Console.ReadLine().
                Split().
                Distinct().
                Select(x => CardIndex(x)).
                ToList();

            var minSuggest = int.MaxValue;

            var maxSuggest = 1 << 10;
            for (int suggest = 0; suggest < maxSuggest; suggest++)
            {
                var distinctCard = cards.Select(x => x & suggest).Distinct().Count();
                if (distinctCard == cards.Count)
                {
                    var suggestSize = SparseBitcount(suggest);
                    if (suggestSize < minSuggest)
                    {
                        minSuggest = suggestSize;
                    }
                }
            }

            Console.WriteLine(minSuggest);
        }

        static int SparseBitcount(int n)
        {
            int count = 0;
            while (n != 0)
            {
                count++;
                n &= (n - 1);
            }
            return count;
        }
    }
}


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

public class Test
{
    [Flags]
    enum Card
    {
        R = 1 << 0,
        G = 1 << 1,
        B = 1 << 2,
        Y = 1 << 3,
        W = 1 << 4,
        One = 1 << 5,
        Two = 1 << 6,
        Three = 1 << 7,
        Four = 1 << 8,
        Five = 1 << 9,
    }

    public static void Main()
    {
        int result = Solve();
        Console.WriteLine(result);
    }

    static int Solve()
    {

        // Don't care for n
        Console.ReadLine();

        var input = Console.ReadLine().Split(' ').Distinct().Select(x => ParseCard(x)).ToArray();
        if (input.Length == 1)
        {
            return 0;
        }
        List<Card> diffs = new List<Card>(input.Length * input.Length);
        for(int i = 0; i < input.Length - 1; i++)
        {
            for(int j = i + 1; j < input.Length; j++)
            {
                Card diff = Diff(input[i], input[j]);
                diffs.Add(diff);
            }
        }

        var subsets = Enumerable.Range(0, 1023).Select(x => (Card)x);
        int min = 11;
        foreach(var subset in subsets)
        {
            if(diffs.All(x => CanDistinguish(subset, x)))
            {
                // This is an answer
                min = Math.Min(min, CountBits((int)subset));
            }
        }

        return min;
    }

    static int CountBits(int num)
    {
        int res = 0;
        while(num > 0)
        {
            if ((num & 1) == 1) res++;
            num >>= 1;
        }
        return res;
    }

    static bool CanDistinguish(Card subset, Card diff)
    {
        return (subset & diff) != 0;
    }

    static Card Diff(Card f, Card s)
    {
        return f ^ s;
    }

    static Card ParseCard(string input)
    {
        Card colour = (Card)Enum.Parse(typeof(Card), input[0].ToString());
        Card num = Card.One;
        switch (input[1])
        {
            case '1': num = Card.One;break;
            case '2': num = Card.Two;break;
            case '3': num = Card.Three;break;
            case '4': num = Card.Four;break;
            case '5': num = Card.Five;break;
        }
        return colour | num;
    }
}


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

namespace CodeForces800
{
    internal static class Program
    {
        public static long prime = 1000000007;
        public static long[] bprime = new long[2];
        public static Dictionary<long, long> invar = new Dictionary<long, long>();
        public static long[] fact = new long[1];
        public static void Main()
        {
            var cur = prime - 2;
            var list = new List<long>();
            while (cur != 0)
            {
                list.Add(cur % 2);
                cur = cur / 2;
            }
            bprime = list.ToArray();
            var str = Console.ReadLine().Split(' ').Select(x => Int32.Parse(x)).ToList();
            var n = str[0];
            var k = str[1];
            long res = 0;
            fact = new long[n + 1];
            fact[0] = 1;
            for (var i = 1; i < n + 1; i++)
            {
                fact[i] = (long)((long)fact[i - 1] * i) % prime;
            }
            for (var i = 0; i <= Math.Min(n,k); i++)
            {
                res += C(n, i);
                res = res % prime;
            }
            Console.WriteLine(res);
        }
        private static long C(long n, long k)
        {
            if (n >= k)
            {
                long res = fact[n];
                res = res * calcInv(fact[n - k]);
                res = res % prime;
                res = res * calcInv(fact[k]);
                res = res % prime;
                return (long)res;
            }
            else return 0;
        }

        public static long calcInv(long n)
        {
            if (invar.TryGetValue(n, out var invn))
                return invn;
            else
            {
                var ost = new long[bprime.Length];
                ost[0] = n;
                for (var i = 1; i < bprime.Length; i++)
                {
                    ost[i] = (ost[i - 1] * ost[i - 1]) % prime;
                }
                long inv = 1;
                for (var i = 0; i < bprime.Length; i++)
                {
                    inv *= (bprime[i] == 1) ? ost[i] : 1;
                    inv = inv % prime;
                }
                invar.Add(n, (long)inv);

                return (long)inv;
            }
        }
    }
}


using System;
using System.Linq;
using CompLib.Util;
using System.Threading;
using System.IO;
using System.Collections.Generic;
using System.Text;
using CompLib.Mathematics;

public class Program
{
    int N, K;
    BinomialCoefficient Binom;
    public void Solve()
    {
        var sc = new Scanner();
        N = sc.NextInt();
        K = sc.NextInt();

        // 2^n人 n回戦トーナメント

        // 優勝が小さい方が良い
        // トーナメントの構築、勝つ人決める

        // K回以下 結果変えられる

        // 可能な勝つ人最小

        if (K >= N)
        {
            Console.WriteLine(ModInt.Pow(2, N));
            return;
        }

        Binom = new BinomialCoefficient(N);
        ModInt ans = 0;
        for (int i = 0; i <= K; i++)
        {
            ans += Binom[N, i];
        }

        Console.WriteLine(ans);

        // 1 1 + N
        // 2 1 + N + 1 + 2 + 3 + ... (N-1)

        // 1 + 3 + (1 + 2)
    }

    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.Linq;

namespace CSharp
{
    class _1060B
    {
        public static void Main()
        {
            long n = long.Parse(Console.ReadLine());
            long a = 0;

            while (a * 10 + 9 < n)
            {
                a = a * 10 + 9;
            }

            long b = n - a;
            Console.WriteLine(a.ToString().Sum(c => c - '0') + b.ToString().Sum(c => c - '0'));
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Codefoeces
{
    class Program
    {
        static void Main(string[] args)
        {

            long n = long.Parse(Console.ReadLine());
            long max = -1;
            long a1 = n / 2;

            long a = 0 ;
            long b = 0; ;
            int i = 1;

            if (n == 1)
            {
                Console.WriteLine(1);
                return;
            }
            while (i < 10 &&  n-b >= 0)
            {
                b = long.Parse(i +""+ new string('9', (int)Math.Log10(a1)) );
                a = n - b;
                if (a >= 0)
                {
                    if (a.ToString().Sum(c => c - '0') + b.ToString().Sum(c => c - '0') > max)
                    {
                        max = a.ToString().Sum(c => c - '0') + b.ToString().Sum(c => c - '0');
                    }
                }
                i++;
            }
            Console.WriteLine(max);

        }
    }
}


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

class Solver
{
	public void Solve()
	{
		var s = CF.ReadLine();
		int res = 0;
		foreach (var c in s)
		{
			res *= 16;
			switch (c)
			{
				case '>': res += 8;  break;
				case '<': res += 9; break;
				case '+': res += 10; break;
				case '-': res += 11; break;
				case '.': res += 12; break;
				case ',': res += 13; break;
				case '[': res += 14; break;
				case ']': res += 15; break;
			}
			res %= 1000003;
		}
		CF.WriteLine(res);
	}

	//  test
	static Utils CF = new Utils(new[]{
@"
,.
"
,
@"
++++[>,.<-]
"

    });
    #region test

    static void Main(string[] args)
    {
#if DEBUG
        for (int t=0;t<CF.TestCount;t++ )
        {
            CF.Test(t);
			var sw = new Stopwatch();
			sw.Start();
            new Solver().Solve();
			Debug.WriteLine("time: "+sw.ElapsedMilliseconds+ " ms");
		}
#else
        new Solver().Solve();
#endif
    }

    class Utils
    {
        public void Test(int t)
        {
            _lines = new List<string>();
            string[] ss = _test_input[t].Replace("\n", "").Split('\r');
            for (int i = 0; i < ss.Length; i++)
            {
                if (
                    (i == 0 || i == ss.Length - 1) &&
                    ss[i].Length == 0
                    )
                    continue;

                _lines.Add(ss[i]);
            }
        }

        public int TestCount
        {
            get
            {
                return _test_input.Length;
            }
        }

        public string ReadLine()
        {
#if DEBUG
            string s = null;
            if (_lines.Count > 0)
            {
                s = _lines[0];
                _lines.RemoveAt(0);
            }
            return s;

#else
            //return _sr.ReadLine();
        return Console.In.ReadLine();
#endif
        }

        public void WriteLine(object o)
        {
#if DEBUG
            System.Diagnostics.Trace.WriteLine(o);
#else
            //_sw.WriteLine(o);
        Console.WriteLine(o);
#endif
        }

        public void Write(object o)
        {
#if DEBUG
            System.Diagnostics.Trace.Write(o);
#else
                //_sw.Write(o);
        Console.Write(o);
#endif
        }

        string[] _test_input;

        List<string> _lines;

#if DEBUG
        public Utils(string[] test_input)
        {
            _test_input = test_input;
        }
#else

        public Utils(string[] dummy)
        {
            //_sr = new System.IO.StreamReader("input.txt");
            //_sw = new System.IO.StreamWriter("output.txt");
        }
#endif

    }

    #endregion
}


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

namespace Codeforces
{
    class A
    {
        private static bool s_time = false;

        static long mod = 1000003;

        private static object Go()
        {
            string s = GetString();

            Dictionary<char, int> map = new Dictionary<char, int>();
            map['>'] = 8;
            map['<'] = 9;
            map['+'] = 10;
            map['-'] = 11;
            map['.'] = 12;
            map[','] = 13;
            map['['] = 14;
            map[']'] = 15;

            long ret = 0;
            for (int i = 0; i < s.Length; i++)
            {
                ret = (ret * 16 + map[s[i]]) % mod;
            }

            return ret;
        }

        #region Template

        public static void Main(string[] args)
        {
            DateTime start = DateTime.Now;
            object output = Go();
            TimeSpan duration = DateTime.Now.Subtract(start);
            if (output != null)
                Wl<string>(output.ToString());
            if (s_time)
                Wl(duration);
        }

        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)
        {
            Console.WriteLine(o.ToString());
        }

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

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


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

class Program
{
    private static void Main(string[] args)
    {
        var tmp = Console.ReadLine().Split(' ');
        var s = tmp[0];
        var k = int.Parse(tmp[1]);

        if (s.Count(ss => ss == '0') < k)
        {
            Console.Write(s.Length - 1);
            return;
        }

        int cnt = 0;
        int zeros = 0;
        for (int i = s.Length - 1; i > 0; i--)
        {
            if (s[i] != '0')
                cnt++;
            else
                zeros++;

            if (zeros == k)
            {
                Console.WriteLine(cnt);
                return;
            }
        }

        Console.Write(0);
    }

    private const int Mod = 1000000000 + 7;

    #region Data Read
    private static char ReadSign()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (ans == '+' || ans == '-' || ans == '?')
                return (char)ans;
        }
    }

    private static long GCD(long a, long b)
    {
        if (a % b == 0) return b;
        return GCD(b, a % b);
    }

    private static List<int>[] ReadGraph(int n, int m)
    {
        List<int>[] g = new List<int>[n];
        for (int i = 0; i < g.Length; i++) g[i] = new List<int>();
        for (int i = 0; i < m; i++)
        {
            int a = RI() - 1;
            int b = RI() - 1;

            g[a].Add(b);
            g[b].Add(a);
        }

        return g;
    }

    private static int[,] ReadGraphAsMatrix(int n, int m)
    {
        int[,] matrix = new int[n + 1, n + 1];
        for (int i = 0; i < m; i++)
        {
            int a = RI();
            int b = RI();
            matrix[a, b] = matrix[b, a] = 1;
        }

        return matrix;
    }

    private static void Sort(ref int a, ref int b)
    {
        if (a > b) Swap(ref a, ref b);
    }

    private static void Swap(ref int a, ref int b)
    {
        int tmp = a;
        a = b;
        b = tmp;
    }

    private const int BufferSize = 1 << 16;
    private static StreamReader consoleReader;
    private static MemoryStream testData;

    private static int RI()
    {
        int ans = 0;
        int mul = 1;
        do
        {
            ans = consoleReader.Read();
            if (ans == -1)
                return 0;
            if (ans == '-') mul = -1;
        } while (ans < '0' || ans > '9');

        ans -= '0';
        while (true)
        {
            int chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans * mul;
            ans = ans * 10 + chr - '0';
        }
    }

    private static ulong RUL()
    {
        ulong ans = 0;
        int chr;
        do
        {
            chr = consoleReader.Read();
            if (chr == -1)
                return 0;
        } while (chr < '0' || chr > '9');

        ans = (uint)(chr - '0');
        while (true)
        {
            chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans;
            ans = ans * 10 + (uint)(chr - '0');
        }
    }

    private static long RL()
    {
        long ans = 0;
        int mul = 1;
        do
        {
            ans = consoleReader.Read();
            if (ans == -1)
                return 0;
            if (ans == '-') mul = -1;
        } while (ans < '0' || ans > '9');

        ans -= '0';
        while (true)
        {
            int chr = consoleReader.Read();
            if (chr < '0' || chr > '9')
                return ans * mul;
            ans = ans * 10 + chr - '0';
        }
    }

    private static int[] RIA(int n)
    {
        int[] ans = new int[n];
        for (int i = 0; i < n; i++)
            ans[i] = RI();
        return ans;
    }

    private static long[] RLA(int n)
    {
        long[] ans = new long[n];
        for (int i = 0; i < n; i++)
            ans[i] = RL();
        return ans;
    }

    private static char[] ReadWord()
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (!((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z')));

        List<char> s = new List<char>();
        do
        {
            s.Add((char)ans);
            ans = consoleReader.Read();
        } while ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'));

        return s.ToArray();
    }

    private static char[] ReadString(int n)
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (!((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z')));

        char[] s = new char[n];
        int pos = 0;
        do
        {
            s[pos++] = (char)ans;
            if (pos == n) break;
            ans = consoleReader.Read();
        } while ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'));

        return s;
    }

    private static char[] ReadStringLine()
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (ans == 10 || ans == 13);

        List<char> s = new List<char>();

        do
        {
            s.Add((char)ans);
            ans = consoleReader.Read();
        } while (ans != 10 && ans != 13 && ans != -1);

        return s.ToArray();
    }

    private static char ReadLetter()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'))
                return (char)ans;
        }
    }
    private static char ReadNonLetter()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (!((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z')))
                return (char)ans;
        }
    }

    private static char ReadAnyOf(IEnumerable<char> allowed)
    {
        while (true)
        {
            char ans = (char)consoleReader.Read();
            if (allowed.Contains(ans))
                return ans;
        }
    }

    private static char ReadDigit()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (ans >= '0' && ans <= '9')
                return (char)ans;
        }
    }

    private static int ReadDigitInt()
    {
        return ReadDigit() - (int)'0';
    }

    private static char ReadAnyChar()
    {
        return (char)consoleReader.Read();
    }

    private static string DoubleToString(double x)
    {
        return x.ToString(CultureInfo.InvariantCulture);
    }

    private static double DoubleFromString(string x)
    {
        return double.Parse(x, CultureInfo.InvariantCulture);
    }

    static Program()
    {
        //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        consoleReader = new StreamReader(Console.OpenStandardInput(BufferSize), Encoding.ASCII, false, BufferSize);
    }

    private static void PushTestData(StringBuilder sb)
    {
        PushTestData(sb.ToString());
    }
    private static void PushTestData(string data)
    {
#if TOLYAN_TEST
        if (testData == null)
        {
            testData = new MemoryStream();
            consoleReader = new StreamReader(testData);
        }

        var pos = testData.Position;
        var bytes = Encoding.UTF8.GetBytes(data);
        testData.Write(bytes, 0, bytes.Length);
        testData.Flush();
        testData.Position = pos;
#endif
    }
    #endregion
}


using System;
class Program
    {
        public static void Main(string[] args)
        {
            string[] input = Console.In.ReadLine().Split(new char[] { ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries);
            int a = int.Parse(input[1]);
            int deleted = 0;
            for(int i = input[0].Length-1; i>0 && a>0; --i)
            {
                if (input[0][i] == '0') a--;
                else deleted++;
            }
            if (a > 0) deleted = input[0].Length - 1;
            Console.WriteLine(deleted);
        }
    }


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

namespace contest
{

    class contest
    {

        static void Main(string[] args)
        {

            //int n = int.Parse(Console.ReadLine());
            //var input = Console.ReadLine().Split().Select(int.Parse).ToArray();

            //var num = Console.ReadLine().Split().Select(int.Parse).ToArray();

            var num = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int a = num[0];
            int target = num[1];
            int dif = num[2];

            if (a == target) Console.WriteLine("YES");
            else if (dif == 0) Console.WriteLine("NO");
            else if (target > a && dif < 0) Console.WriteLine("NO");
            else if (target < a && dif > 0) Console.WriteLine("NO");
            else if ((target - a) % dif == 0) Console.WriteLine("YES");
            else Console.WriteLine("NO");

            //Console.WriteLine();

            //Console.Read();

        }

    }

}


using System;

namespace ConsoleApplication16
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split(' ');
            int[] n = Array.ConvertAll(s, int.Parse);

            if (n[2] == 0)
            {
                if (n[1] == n[0])
                {
                    Console.WriteLine("YES");
                }
                else
                {
                    Console.WriteLine("NO");
                }
            }

            else if ((n[1] < n[0] && n[2] > 0) || (n[1] > n[0] && n[2] < 0))
            {
                Console.WriteLine("NO");
            }
            else
            {
                if ((n[1] - n[0]) % n[2] == 0)
                {
                    Console.WriteLine("YES");
                }
                else
                {
                    Console.WriteLine("NO");
                }
            }
        }

    }

}


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

namespace AlgoTraining.Codeforces.D_s
{
    public class FastScanner : StreamReader
    {
        private string[] _line;
        private int _iterator;

        public FastScanner(Stream stream) : base(stream)
        {
            _line = null;
            _iterator = 0;
        }
        public int NextInt()
        {
            if (_line == null || _iterator >= _line.Length)
            {
                _line = base.ReadLine().Split(' ');
                _iterator = 0;
            }
            if (_line.Count() == 0) throw new IndexOutOfRangeException("Input string is empty");
            return Convert.ToInt32(_line[_iterator++]);
        }
        public long NextLong()
        {
            if (_line == null || _iterator >= _line.Length)
            {
                _line = base.ReadLine().Split(' ');
                _iterator = 0;
            }
            if (_line.Count() == 0) throw new IndexOutOfRangeException("Input string is empty");
            return Convert.ToInt64(_line[_iterator++]);
        }
    }
    class IteratedLinearFunctionECR13
    {
        private static int _mod = (int)1e9 + 7;
        public static void Main(string[] args)
        {
            using (FastScanner fs = new FastScanner(new BufferedStream(Console.OpenStandardInput())))
            using (StreamWriter writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
            {
                long A = fs.NextLong(), B = fs.NextLong(), n = fs.NextLong(), x = fs.NextLong();
                if (n == 0) writer.WriteLine(x);
                else if (n == 1) writer.WriteLine((A * x + B) % _mod);
                else
                {
                    long[,] initial = new long[,] { { A * x + B, 1 } };
                    long[,] factor = new long[,] { { A, 0 }, { B, 1 } };
                    long[,] res = MultiplyMatricesMod(initial, BinPowMatrixMod(factor, n - 1, _mod), _mod);
                    writer.WriteLine(res[0, 0]);
                }
            }
        }
        public static long BinPow(long a, long p)
        {
            if (p == 0) return 1;
            if ((p & 1) == 0)
            {
                long t = BinPow(a, p / 2);
                return t * t;
            }
            else
            {
                return a * BinPow(a, p - 1);
            }
        }
        public static long BinPowMod(long a, long p, long mod)
        {
            if (p == 0) return 1;
            if ((p & 1) == 0)
            {
                long t = BinPow(a, p / 2);
                return (t * t) % mod;
            }
            else
            {
                return (a % mod * BinPow(a, p - 1)) % mod;
            }
        }

        public static long[,] BinPowMatrix(long[,] a, long p) // p >= 1
        {
            if (a.GetLength(0) != a.GetLength(1))
            {
                throw new Exception("Not a square matrix");
            }

            if (p == 1) return a;
            if ((p & 1) == 0)
            {
                long[,] t = BinPowMatrix(a, p / 2);
                return MultiplyMatrices(t, t);
            }
            else
            {
                return MultiplyMatrices(a, BinPowMatrix(a, p - 1));
            }
        }

        public static long[,] BinPowMatrixMod(long[,] a, long p, long mod) // p >= 1
        {
            if (a.GetLength(0) != a.GetLength(1))
            {
                throw new Exception("Not a square matrix");
            }

            if (p == 1) return a;
            if ((p & 1) == 0)
            {
                long[,] t = BinPowMatrixMod(a, p / 2, mod);
                return MultiplyMatricesMod(t, t, mod);
            }
            else
            {
                return MultiplyMatricesMod(a, BinPowMatrixMod(a, p - 1, mod), mod);
            }
        }

        private static long[,] MultiplyMatrices(long[,] a, long[,] b)
        {
            if (a.GetLength(1) == b.GetLength(0))
            {
                long[,] c = new long[a.GetLength(0), b.GetLength(1)];
                for (int i = 0; i < c.GetLength(0); i++)
                {
                    for (int j = 0; j < c.GetLength(1); j++)
                    {
                        c[i, j] = 0;
                        for (int k = 0; k < a.GetLength(1); k++)
                            c[i, j] = c[i, j] + a[i, k] * b[k, j];
                    }
                }
                return c;
            }
            else
            {
                throw new Exception("Can't multiply because of incompatible sizes");
            }
        }

        private static long[,] MultiplyMatricesMod(long[,] a, long[,] b, long mod)
        {
            if (a.GetLength(1) == b.GetLength(0))
            {
                long[,] c = new long[a.GetLength(0), b.GetLength(1)];
                for (int i = 0; i < c.GetLength(0); i++)
                {
                    for (int j = 0; j < c.GetLength(1); j++)
                    {
                        c[i, j] = 0;
                        for (int k = 0; k < a.GetLength(1); k++)
                        {
                            c[i, j] = c[i, j] + a[i, k] % mod * b[k, j] % mod;
                            c[i, j] %= mod;
                        }
                    }
                }
                return c;
            }
            else
            {
                throw new Exception("Can't multiply because of incompatible sizes");
            }
        }

        private static long[,] MatrixMod(long[,] a, long mod)
        {
            long[,] b = new long[a.GetLength(0), a.GetLength(1)];
            for (int i = 0; i < a.GetLength(0); i++)
            {
                for (int j = 0; j < a.GetLength(1); j++)
                {
                    b[i, j] = a[i, j] % mod;
                }
            }
            return b;
        }
    }
}


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

    }

}