using System;
using System.Collections.Generic;

namespace Exercise4
{
    class Program
    {
        static void Main(string[] args)//https://codeforces.com/contest/1286/problem/A
        {
            int n = Int32.Parse(Console.ReadLine()),
                lostSwitch;
            int[] p = new int[n];
            bool[] b = new bool[n];
            bool nothing = true;
            Stack<int>[] lost = new Stack<int>[2];
            lost[0] = new Stack<int>();
            lost[1] = new Stack<int>();

            string[] s = Console.ReadLine().Split(' ');
            for (int i = 0; i < n; i++)
            {
                p[i] = Int32.Parse(s[i]);
                if (p[i] != 0)
                    b[p[i] - 1] = true;
            }
            for (int i = 0; i < n; i++)
            {
                if (b[i])
                {
                    nothing = false;
                    break;
                }
            }
            for (int i = 0; i < n; i++)
                if (!b[i])
                    lost[(i + 1) % 2].Push(i + 1);

            if (nothing)//все 0
            {
                int k = 0;
                for (int i = 0; i < lost.Length; i++)
                    while (lost[i].Count > 0)
                        p[k++] = lost[i].Pop();
            }
            else
            {
                int firstNumberIndex = 0,
                    lastNumberIndex = n - 1;
                while (p[firstNumberIndex] == 0)
                    firstNumberIndex++;
                while (p[lastNumberIndex] == 0)
                    lastNumberIndex--;

                int range = 0,
                    firstNumberIndexSwitch = p[firstNumberIndex] % 2; //чтобы 5 раз заного не расчитывать
                lostSwitch = firstNumberIndexSwitch;//этот свич будем постоянно менять

                for (int i = firstNumberIndex + 1; i < lastNumberIndex; i++)//дырки
                    if (p[i] == 0)
                        range++;
                    else
                    {
                        if (p[i] % 2 == lostSwitch)
                            if (range <= lost[lostSwitch].Count)
                                for (int j = 1; j <= range; j++)
                                    p[i - j] = lost[lostSwitch].Pop();
                            else
                                lostSwitch = (lostSwitch + 1) % 2;
                        range = 0;
                    }

                lostSwitch = p[lastNumberIndex] % 2;

                if (n - lastNumberIndex - 1 >= lost[lostSwitch].Count)
                    for (int i = lastNumberIndex + 1; i < n; i++)//вперед от lastNumber (только числа =%2)
                        p[i] = lost[lostSwitch].Pop();

                lostSwitch = firstNumberIndexSwitch;

                if (firstNumberIndex >= lost[lostSwitch].Count)//назад от firstNumber (только числа =%2)
                    for (int i = firstNumberIndex - 1; i >= 0; i--)
                        p[i] = lost[lostSwitch].Pop();

                lostSwitch = firstNumberIndexSwitch;

                if (lost[0].Count != 0 || lost[1].Count != 0)//вперед от firstNumber (все числа)
                    for (int i = firstNumberIndex + 1; i < n; i++)
                        if (p[i] != 0)
                            lostSwitch = p[i] % 2;
                        else if (lost[lostSwitch].Count > 0)
                            p[i] = lost[lostSwitch].Pop();
                        else
                        {
                            lostSwitch = (lostSwitch + 1) % 2;
                            p[i] = lost[lostSwitch].Pop();
                        }

                lostSwitch = firstNumberIndexSwitch;

                if (lost[0].Count != 0 || lost[1].Count != 0)//назад от firstNumber (все числа)
                    for (int i = firstNumberIndex - 1; i >= 0; i--)
                        if (p[i] != 0)
                            lostSwitch = p[i] % 2;
                        else if (lost[lostSwitch].Count > 0)
                            p[i] = lost[lostSwitch].Pop();
                        else
                        {
                            lostSwitch = (lostSwitch + 1) % 2;
                            p[i] = lost[lostSwitch].Pop();
                        }
            }
            int win = 0;
            lostSwitch = p[0] % 2;

            for (int i = 1; i < n; i++)//подсчет
                if (p[i] % 2 != lostSwitch)
                {
                    win++;
                    lostSwitch = (lostSwitch + 1) % 2;
                }
            Console.WriteLine(win);
        }

    }
}


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

namespace KROK_QR
{

    class TaskD
    {
        static void Main(string[] args)
        {

            int a, n, i, j, max_sqrt;
            long p;
            double a_sqrt;
            string str;
            string[] s = new string[2];
            str = Console.ReadLine();
            s = str.Split();
            a = int.Parse(s[0]);
            n = int.Parse(s[1]);

            int[] squares = new int[3162];
            p = 0;

            for (i = 0; i < 3162; i++)
                squares[i] = (i + 1) * (i + 1);

            for (i = 0; i < n; i++, a++)
            {
                a_sqrt = Math.Sqrt(a);
                max_sqrt = (int)Math.Truncate(a_sqrt);

                for (j = max_sqrt - 1; j >= 0; j--)
                {
                    //Console.WriteLine(a + " " + j + " " + squares[j]);
                    if (a % squares[j] == 0)
                    {
                        p += a / squares[j];
                        break;
                    }
                }
            }

            Console.Write(p);

        }
    }
}


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

namespace Calendar
{
    class Program
    {
        static void Main(string[] args)
        {
            int v = 3200;
            long a,n,j,i,p,an,k;
            long[] kv = new long[v+1];
            long[] my = new long [1000001];
            string s;
            string[] ss;

            s = Console.ReadLine();
            ss = s.Split();
            a = Convert.ToInt32(ss[0]);
            n = Convert.ToInt32(ss[1]);
  // a:=1;
  // n := 9;
            p  = 0;
            an = a + n - 1;

            for (i = 1; i <= v; i++) kv[i] = i*i;

            for (i = a; i <= an; i++) my[i] = 1;

            for (i = 2; i <= v; i++)
            {

                for (j = 1; j <= v; j++)
                {
                    k = kv[i] * j;
                    if (k < a) continue;
                    if (k > an) break;
                    my[k] = kv[i];
                }
            }

            for (i = a; i <= an; i++) p = p + i/my[i];

              Console.WriteLine(p);

        }
    }
}


using System;
using System.Collections.Generic;

namespace CrokContest
{
    class Program
    {
        static void Main(string[] args)
        {
            var arr = Console.ReadLine().Split();
            int a = int.Parse(arr[0]);
            int n = int.Parse(arr[1]);

            int end = a + n -1;

            int sqrLen = 1;
            int[] table = new int[3163];
            table[0] = 1;
            for (int i = 1; table[i-1] < end; ++i, ++sqrLen)
                table[i] = 1 + i*2 + table[i -1];

            int max = end+1;
            int[] sqrs = new int[max];
            for (int i = 0; i < sqrLen; ++i)
            {
                for (int j = table[i]; j < max; j += table[i])
                {
                    sqrs[j] = table[i];
                }
            }

            Decimal sum = 0;
            for (int i = a; i <= end; ++i)
            {
                sum += i / sqrs[i];
            }
            Console.Write(sum);
        }
    }
}

k


using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Web;

class Program
{
    static int Max(int a1, int a2, int a3)
    {
        int max = a1 > a2 ? a1 : a2;
        return a3 > max ? a3 : max;
    }

    static int Max(int a1, int a2)
    {
        return a1 > a2 ? a1 : a2;
    }

    static void Main(string[] args)
    {
        var str = Console.ReadLine().Split(' ').Select(int.Parse).ToList();

        int n = str[0];
        int k = str[1];
        int BG = 1000000007;

        int[,] dp = new int [n+1, k+1];

        for (int i = 0; i <= n; i++)
        {
            dp[i,1] = 1;
        }

        for (int i = 0; i <= k; i++)
        {
            dp[1,i] = 1;
        }

        for (int j = 2; j <= k; j++)
        {
            for (int i = 2; i <= n; i++)
            {
                int sum = 0;
                int exp = 1;
                while (i >= exp)
                {
                    if (i % exp == 0)
                    {
                        sum = (sum + dp[i / exp, j - 1]) % BG;
                    }

                    exp++;
                }

                dp[i, j] = sum;
            }
        }

        int res = 0;
        for (int i = 1; i <= n; i++)
        {
            res = (res + dp[i, k]) % BG;
        }

        Console.WriteLine(res);
    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Web;

class Program
{
    static int Max(int a1, int a2, int a3)
    {
        int max = a1 > a2 ? a1 : a2;
        return a3 > max ? a3 : max;
    }

    static int Max(int a1, int a2)
    {
        return a1 > a2 ? a1 : a2;
    }

    static void Main(string[] args)
    {
        var str = Console.ReadLine().Split(' ').Select(int.Parse).ToList();

        int N = str[0];
        int K = str[1];
        int mod = 1000000007;

        int[,] dp = new int [N+1, K+1];

        dp[0,1] = 1;
        for (int k = 1; k <= K; k++)
        for (int n = 1; n <= N; n++)
        for (int l = n; l <= N; l += n)
            dp[k,l] = (dp[k,l] + dp[k - 1,n]) % mod;

        var ans = 0;
        for (int n = 1; n <= N; n++)
            ans = (ans + dp[K,n]) % mod;

        Console.WriteLine(ans);
    }

}


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

namespace CodeForces {
    struct Node {
        public int X, Y, D;
        public Node(int x,int y, int d) {
            X = x;
            Y = y;
            D = d;
        }
    }

    class Cf {
        static TextReader input;
        static void Main(string[] args) {
#if TESTS
            Stopwatch sw = new Stopwatch();
            input = new StreamReader("input.txt");
#else
            input = Console.In;
#endif
            Solve();
#if TESTS
            Console.WriteLine();
            Console.WriteLine("Milliseconds: {0}", sw.ElapsedMilliseconds);
            Console.ReadLine();
#endif
        }
        const int MOD = 1000000007;
        static int n, m, k;
        static void Solve() {
            string s = ReadLine();
            string t = ReadLine();
            k = ReadInt();
            n = s.Length;
            int a = 0;
            for (int i = 0; i < n; i++) {
                string s1 = s.Substring(0, i);
                string s2 = s.Substring(i);
                if (s2 + s1 == t)
                    ++a;
            }
            int b = n - a;
            int[] da = new int[k+1];
            int[] db = new int[k+1];
            if (s == t)
                da[0] = 1;
            else
                db[0] = 1;
            for (int i = 1; i <= k; i++) {
                da[i] = (da[i - 1] * (a - 1) + db[i - 1] * a) % MOD;
                db[i] = (da[i - 1] * b + db[i - 1] * (b - 1)) % MOD;
            }
            Console.WriteLine(da[k]);
        }

        static int[] Z_function(string s) {
            int n = s.Length;
            int[] z = new int[n];
            for (int i = 1, l = 0, r = 0; i < n; ++i) {
                if (i <= r)
                    z[i] = Math.Min(r - i + 1, z[i - l]);
                while (i + z[i] < n && s[z[i]] == s[i + z[i]])
                    ++z[i];
                if (i + z[i] - 1 > r) {
                    l = i; r = i + z[i] - 1;
                }
            }
            return z;
        }

        static int SquaredDistanceBetweenSegments(int x1, int y1, int x2, int y2, int xx1, int yy1, int xx2, int yy2) {
            return Math.Min(Math.Min(SquaredDistanceToSegment(x1, y1, xx1, yy1, xx2, yy2), SquaredDistanceToSegment(x2, y2, xx1, yy1, xx2, yy2)),
                Math.Min(SquaredDistanceToSegment(xx1, yy1, x1, y1, x2, y2), SquaredDistanceToSegment(xx2, yy2, x1, y1, x2, y2)));
        }

        static int SquaredDistanceToSegment(int x, int y, int x1, int y1, int x2, int y2) {
            int result = Math.Min(SquaredDistance(x, y, x1, y1), SquaredDistance(x, y, x2, y2));
            if (x1 == x2 && y1 <= y && y <= y2)
                result = (x - x1) * (x - x1);
            else if (y1 == y2 && x1 <= x && x <= x2)
                result = (y - y1) * (y - y1);
            return result;
        }

        static int SquaredDistance(int ax, int ay, int bx, int by) {
            return (ax - bx) * (ax - bx) + (ay - by) * (ay - by);
        }

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

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

        public static string ReadLine() {
            return input.ReadLine();
        }

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

    public class SegmentTree {
        private int[] a, t;
        private int n;
        public SegmentTree(int[] a) {
            n = a.Length;
            this.a = a;
            t = new int[n << 2];
            buildSegmentTree(0, n - 1, 1);
        }

        private void buildSegmentTree(int l, int r, int v) {
            if (l == r)
                t[v] = a[l];
            else {
                int m = (l + r) >> 1;
                int vl = v << 1;
                int vr = (v << 1) | 1;
                buildSegmentTree(l, m, vl);
                buildSegmentTree(m + 1, r, vr);
                t[v] = t[vl] + t[vr];
            }
        }

        public int QuerySegmentTree(int l, int r) {
            return querySegmentTree(1, l, r, 0, n - 1);
        }

        public void Update(int v, int tl, int tr, int pos, int new_val) {
            if (tl == tr)
                t[v] = new_val;
            else {
                int tm = (tl + tr) / 2;
                if (pos <= tm)
                    Update(v << 1, tl, tm, pos, new_val);
                else
                    Update(v << 1 + 1, tm + 1, tr, pos, new_val);
                t[v] = t[v << 1] + t[v << 1 + 1];
            }
        }

        private int querySegmentTree(int v, int l, int r, int tl, int tr) {
            if (l > r)
                return 0;
            if (l == tl && r == tr)
                return t[v];
            int m = (tl + tr) >> 1;
            return querySegmentTree(v << 1, l, Math.Min(r, m), tl, m) + querySegmentTree((v << 1) | 1, Math.Max(l, m + 1), r, m + 1, tr);
        }
    }
    class Graph : List<List<int>> {
        public Graph(int num): base(num) {
            for (int i = 0; i < num; i++) {
                this.Add(new List<int>());
            }
        }
    }
    class Heap<T> : IEnumerable<T> where T : IComparable<T> {
        private List<T> heap = new List<T>();
        private int heapSize;
        private int Parent(int index) {
            return (index - 1) >> 1;
        }
        public int Count {
            get { return heap.Count; }
        }
        private int Left(int index) {
            return (index << 1) | 1;
        }
        private int Right(int index) {
            return (index << 1) + 2;
        }
        private void Max_Heapify(int i) {
            int l = Left(i);
            int r = Right(i);
            int largest = i;
            if (l < heapSize && heap[l].CompareTo(heap[i]) > 0)
                largest = l;
            if (r < heapSize && heap[r].CompareTo(heap[largest]) > 0)
                largest = r;
            if (largest != i) {
                T temp = heap[largest];
                heap[largest] = heap[i];
                heap[i] = temp;
                Max_Heapify(largest);
            }
        }
        private void BuildMaxHeap() {
            for (int i = heap.Count >> 1; i >= 0; --i)
                Max_Heapify(i);
        }

        public IEnumerator<T> GetEnumerator() {
            return heap.GetEnumerator();
        }

        public void Sort() {
            for (int i = heap.Count - 1; i > 0; --i) {
                T temp = heap[i];
                heap[i] = heap[0];
                heap[0] = temp;
                --heapSize;
                Max_Heapify(0);
            }
        }

        public T Heap_Extract_Max() {
            T max = heap[0];
            heap[0] = heap[--heapSize];
            Max_Heapify(0);
            return max;
        }

        public void Clear() {
            heap.Clear();
            heapSize = 0;
        }

        public void Insert(T item) {
            if (heapSize < heap.Count)
                heap[heapSize] = item;
            else
                heap.Add(item);
            int i = heapSize;
            while (i > 0 && heap[Parent(i)].CompareTo(heap[i]) < 0) {
                T temp = heap[i];
                heap[i] = heap[Parent(i)];
                heap[Parent(i)] = temp;
                i = Parent(i);
            }
            ++heapSize;
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return ((IEnumerable)heap).GetEnumerator();
        }
    }
    public class Treap {
        private static Random rand = new Random();
        public static Treap Merge(Treap l, Treap r) {
            if (l == null) return r;
            if (r == null) return l;
            Treap res;
            if (l.y > r.y) {
                Treap newR = Merge(l.right, r);
                res = new Treap(l.x, l.y, l.left, newR);
            }
            else {
                Treap newL = Merge(l, r.left);
                res = new Treap(r.x, r.y, newL, r.right);
            }
            return res;
        }

        public void Split(int x, out Treap l, out Treap r) {
            Treap newTree = null;
            if (this.x <= x) {
                if (right == null)
                    r = null;
                else
                    right.Split(x, out newTree, out r);
                l = new Treap(this.x, y, left, newTree);
            }
            else {
                if (left == null)
                    l = null;
                else
                    left.Split(x, out l, out newTree);
                r = new Treap(this.x, y, newTree, right);
            }
        }

        public Treap Add(int x) {
            Treap l, r;
            Split(x, out l, out r);
            Treap m = new Treap(x, rand.Next());
            return Merge(Merge(l, m), r);
        }

        public Treap Remove(int x) {
            Treap l, m, r;
            Split(x - 1, out l, out r);
            r.Split(x, out m, out r);
            return Merge(l, r);
        }

        private int x, y, cost, maxTreeCost;
        private Treap left, right;
        public Treap(int x, int y, Treap l, Treap r) {
            this.x = x;
            this.y = y;
            left = l;
            right = r;
        }
        public Treap(int x, int y) : this(x, y, null, null) { }
        public void InOrder() {
            inOrder(this);
        }
        private void inOrder(Treap t) {
            if (t == null) return;
            inOrder(t.left);
            Console.WriteLine(t.x);
            inOrder(t.right);
        }
    }
    public static class Extensions {
        public static void Fill(this int[] array, int val) {
            for (int i = 0; i < array.Length; i++) {
                array[i] = val;
            }
        }

        public static void Fill(this double[] array, double val) {
            for (int i = 0; i < array.Length; i++) {
                array[i] = val;
            }
        }

        public static int ToInt(this string s) {
            return int.Parse(s);
        }

        public static string Fill(this char c, int count) {
            char[] r = new char[count];
            for (int i = 0; i < count; ++i)
                r[i] = c;
            return new string(r);
        }

        public static void Print<T>(this IEnumerable<T> arr) {
            foreach (T t in arr)
                Console.Write("{0} ", t);
        }
    }
}


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 D
    {
        private static ThreadStart s_threadStart = new D().Go;
        private static bool s_time = false;

        private void Go()
        {
            string a = GetString();
            int n = a.Length;
            string b = GetString();
            long k = GetInt();

            long mod = 1000000007;
            long[,] dp = new long[2, 100001];
            dp[0, 1] = 0;
            dp[1, 1] = 1;
            for (int i = 2; i <= k; i++)
            {
                dp[0, i] = ((n - 1) * dp[1, i - 1]) % mod;
                dp[1, i] = ((n - 2) * dp[1, i - 1] + dp[0, i - 1]) % mod;
            }

            long ret = 0;
            if (a == b) ret += dp[0, k];
            for (int i = 0; i < n-1; i++)
            {
                a = a[n - 1] + a.Substring(0, n - 1);
                if (a == b) ret = (ret+dp[1, k]) % mod;
            }

            Wl(ret);
        }

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


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

namespace z3
{
    class Program
    {
        static private int gcd(int x, int y)
        {
            return (x>0) ? gcd(y%x,x) : y;
        }

        static private int max(int a, int b)
        {
            return (a>b)?a:b;
        }

        static private int nextHc(int x, int y, int m, int h)
        {
            long tt = (long)x * (long)h + (long)y;
            return (int)(tt%(long)m);
        }

        static private void swapvars(ref int a, ref int b)
        {
            int k = b;
            b = a;
            a = k;
        }

        static private void calc(ref int m, ref int x1, ref int y1, ref int h1, ref int a1, ref int x2, ref int y2, ref int h2, ref int a2, ref int period1, ref int period2)
        {
            long t = 1;
            List<int> hs = new List<int>(capacity: m);
            if(period1 <= period2)
            {
                swapvars(ref x1,ref x2);
                swapvars(ref y1,ref y2);
                swapvars(ref h1,ref h2);
                swapvars(ref a1,ref a2);
                swapvars(ref period1, ref period2);
            }
            while(h2 != a2)
            {
                h1 = nextHc(x1, y1, m, h1);
                h2 = nextHc(x2, y2, m, h2);
                if((h1 == a1) && (h2 == a2))
                {
                    Console.Write(t);
                    return;
                }
                ++t;
            }
            //h2 == a2 now
            hs[0] = h1;
            for(int i = 1; i < period1; ++i) hs[i] = nextHc(x1, y1, m, hs[i-1]);
            int k = 0;
            while(true)
            {
                k += period2;
                k %= period1;
                h1 = hs[k];
                t += (long)period2;
                if(h1 == a1)
                {
                    Console.Write(t);
                    return;
                }
            }
            return;
        }

        static void Main(string[] args)
        {
            int m;
            int h1, a1, x1, y1, h2, a2, x2, y2;
            string ms = Console.ReadLine();
            m = Convert.ToInt32(ms);
            string[] ha1 = Console.ReadLine().Split(null);
            h1 = Convert.ToInt32(ha1[0]);
            a1 = Convert.ToInt32(ha1[1]);
            string[] xy1 = Console.ReadLine().Split(null);
            x1 = Convert.ToInt32(xy1[0]);
            y1 = Convert.ToInt32(xy1[1]);
            string[] ha2 = Console.ReadLine().Split(null);
            h2 = Convert.ToInt32(ha2[0]);
            a2 = Convert.ToInt32(ha2[1]);
            string[] xy2 = Console.ReadLine().Split(null);
            x2 = Convert.ToInt32(xy2[0]);
            y2 = Convert.ToInt32(xy2[1]);
            int t = 1;
            int h1saved = h1, h2saved = h2;
            int period1 = 0, period2 = 0;
            for (int i = 0; i < m + 1; ++i)
            {
                h1 = nextHc(x1, y1, m, h1);
                h2 = nextHc(x2, y2, m, h2);
                if ((h1 == a1) && (h2 == a2))
                {
                    Console.Write(t);
                    return;
                }
                ++t;
            }
            int h1prev = h1, h2prev = h2;
            int a1flag = 0;
            int a2flag = 0;
            do
            {
                h1 = nextHc(x1, y1, m, h1);
                ++period1;
                if ((h1 == a1) && (a1flag == 0)) a1flag = 1;
            } while (h1 != h1prev);
            do
            {
                h2 = nextHc(x2, y2, m, h2);
                ++period2;
                if ((h2 == a2) && (a2flag == 0)) a2flag = 1;
            } while (h2 != h2prev);

            if ((a1flag == 0) || (a2flag == 0))
            {
                Console.Write("-1");
                return;
            }

            if ((gcd(period1, period2) == 1) && (period1 > 1) && (period2 > 1))
            {
                calc(ref m, ref x1, ref y1, ref h1saved, ref a1, ref x2, ref y2, ref h2saved, ref a2, ref period1, ref period2);
                return;
            }
            else
            {
                Console.Write("-1");
                return;
            }
        }
    }
}


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

namespace C
{
	class Program
	{
		static void Main(string[] args)
		{
			var m = RInt();
			var a = R2Int();
			var axy = R2Int();
			var b = R2Int();
			var bxy = R2Int();

			var first = new int[] { a[0], b[0] };

			var ticks = 0;
			var l1 = new int[] { -1, -1 };
			var l2 = new int[] { -1, -1 };

			while (true)
			{
				ticks++;
				a[0] = Next(a, axy, m);
				b[0] = Next(b, bxy, m);

				if (a[0] == a[1] && b[0] == b[1])
				{
					Console.WriteLine(ticks);
					return;
				}

				if (!Update(a, l1, first[0], ticks) || !Update(b, l2, first[1], ticks))
				{
					Console.WriteLine("-1");
					return;
				}
				if (l1[0] != -1 && l2[0] != -1)
					break;

				Update2(a, l1, ticks);
				Update2(b, l2, ticks);
			}

			var x = l1[1];
			for (var i = 0; i <= m; i++)
			{
				x += l1[0];
				var c = x % l2[0];
				if (c == l2[1])
				{
					Console.WriteLine(x);
					return;
				}
			}
			Console.WriteLine("-1");
		}

		static int RInt()
		{
			return int.Parse(Console.ReadLine());
		}
		static int[] R2Int()
		{
			return Console.ReadLine().Split(' ').Select(v => int.Parse(v)).ToArray();
		}

		static int Next(int[] v, int[] xy, int m)
		{
			return (xy[0] * v[0] + xy[1]) % m;
		}
		static bool Update(int[] v, int[] l, int first, int ticks)
		{
			if (l[0] == -1 && v[0] == first)
			{
				l[0] = ticks;
				if (l[1] == -1)
					return false;
			}
			return true;
		}
		static void Update2(int[] v, int[] l, int ticks)
		{
			if (l[1] == -1 && v[0] == v[1])
				l[1] = ticks;
		}
	}
}


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

namespace C
{
	class Measurer : IDisposable
	{
		public Measurer()
		{
			sw = new Stopwatch();
			sw.Start();
		}

		Stopwatch sw { get; set; }

		public void Dispose()
		{
			sw.Stop();
			//Console.WriteLine(sw.Elapsed.ToString());
		}
	}

	class Program
	{
		static void Main(string[] args)
		{
			var m = RInt();
			var a = R2Int();
			var axy = R2Int();
			var b = R2Int();
			var bxy = R2Int();

			var first = new int[] { a[0], b[0] };

			long ticks = 0;
			//var l1 = new int[] { -1, -1 };
			//var l2 = new int[] { -1, -1 };
			var p1 = new long[] { -1, -1 };
			var p1i = 0;
			var p2 = new long[] { -1, -1 };
			var p2i = 0;

			using (var me = new Measurer())
			{
				for (var i = 0; i <= 2 * m; i++)
				{
					ticks++;
					a[0] = Next(a, axy, m);
					b[0] = Next(b, bxy, m);
					if (a[0] == a[1])
						p1[p1i++] = ticks;
					if (b[0] == b[1])
						p2[p2i++] = ticks;
					if (p1i > 1 && p2i > 1)
						break;
				}
				if (p1i < 2 || p2i < 2)
				{
					Console.WriteLine("-1");
					return;
				}
				if(p1[0] == p2[0] || p1[0] == p2[1])
				{
					Console.WriteLine(p1[0]);
					return;
				}
				if(p1[1] == p2[0] || p1[1] == p2[1])
				{
					Console.WriteLine(p1[0]);
					return;
				}
			}

			using (var me = new Measurer())
			{
				long x = p1[0];
				long dx = p1[1] - p1[0];
				long dp2 = p2[1] - p2[0];
				for (var i = 0; i <= m; i++)
				{
					x += dx;
					var k = (x - p2[0]) % dp2;
					if (k == 0)
					{
						Console.WriteLine(x);
						return;
					}
				}
			}
			Console.WriteLine("-1");
			Console.ReadLine();
		}

		static int RInt()
		{
			return int.Parse(Console.ReadLine());
		}
		static int[] R2Int()
		{
			return Console.ReadLine().Split(' ').Select(v => int.Parse(v)).ToArray();
		}

		static int Next(int[] v, int[] xy, int m)
		{
			return (int)(((long)xy[0] * (long)v[0] + (long)xy[1]) % m);
		}
	}
}


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

namespace задачи
{
    class Program
    {
        static void Main(string[] args)
        {
            int k, l, m, n, d,a=0;
            k = Convert.ToInt16(Console.ReadLine());
            l = Convert.ToInt16(Console.ReadLine());
            m = Convert.ToInt16(Console.ReadLine());
            n = Convert.ToInt16(Console.ReadLine());
            d = Convert.ToInt16(Console.ReadLine());//dlina
            int[,] b = new int[d,2];
            for (int i = 0; i < d; i++)
            {
                b[i,0] = i + 1;
            }

            for (int i = k-1; i < d; i+=k)
            {
                b[i, 1] = 1;
            }
            for (int i = l-1; i < d; i += l)
            {
                b[i, 1] = 1;
            }
            for (int i = m-1; i < d; i += m)
            {
                b[i, 1] = 1;
            }
            for (int i = n-1; i < d; i += n)
            {
                b[i, 1] = 1;
            }

            for (int i = 0; i < d; i++)
            {
                if (b[i, 1] == 1) { a++; }
            }
            Console.WriteLine(a);
          //  Console.ReadLine();
        }
    }
}


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

namespace ConsoleApp9
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] S = Console.ReadLine().Split();
            long n = Convert.ToInt64(S[0]);
            long m = Convert.ToInt64(S[1]);
            if (m == 0) Console.WriteLine(n + " " + n);
            else Console.WriteLine(Math.Max(0, n - (m * 2)) + " " + Math.Max(0, n - F(m)));
        }

        static int F(long r)
        {
            long c = r * 2;
            for (int i = 1; i <= r + 1; i++)
            {
                if (i * (i - 1) == c) return i;
                else if (i * (i - 1) > c) return i;
            }
            return 0;
        }
    }
}


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

namespace Codeforces
{
	static class Program
	{

		static void Main(string[] args)
		{
			var nm = Console.ReadLine().Split().Select(int.Parse).ToList();
			int min = nm[0], max = nm[0];
			int rem = nm[1], cur = 0;
			if (nm[1] != 0)
			{
				min = nm[0] - nm[1] * 2;

				while(rem > 0)
				{
					var d = Math.Min(cur, rem);
					cur++;
					rem -= d;
				}
				if(cur != 1) max = nm[0] - cur;
			}
			Console.WriteLine($"{Math.Max(min, 0)} {Math.Max(max, 0)}");
			Console.ReadLine();
		}
	}
}


using System;
using System.Linq;

namespace _626C
{
    class Program
    {
        static void Main(string[] args)
        {
            var s = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var n = s[0]; var m = s[1];
            int i = 0;
            int j = 0;
            int[] tower = new int[3*1000*1000+3];
            while (m > 0)
            {
                j += 3; m--; tower[j]++;
            }
            while (n > 0)
            {
                i += 2;
                if (tower[i] == 0)
                {
                    n--; tower[i]++;
                }
            }
            Console.WriteLine(Math.Max(i,j));
        }
    }
}


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

namespace AlgoTraining.Codeforces.A_s
{

    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 RoundHouse346
    {
        public static void Main(string[] args)
        {
            using (FastScanner fs = new FastScanner(new BufferedStream(Console.OpenStandardInput())))
            using (StreamWriter writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
            {
                int n = fs.NextInt(), a = fs.NextInt() - 1, b = fs.NextInt();
                b = b / Math.Abs(b) * (Math.Abs(b) % n);
                int ans = a + b;
                if (ans >= n) ans %= n;
                else if (ans < 0) ans = n + ans;
                writer.WriteLine(ans + 1);
            }
        }
    }
}


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

class Program
{
    string[] board = new string[8];

    static void Main(string[] args)
    {
        new Program().Solve();
    }

    void Solve()
    {
        for (int i = 0; i < 8; i++)
        {
            board[i] = Console.ReadLine();
        }

        if (DFS(7, 0, 0)) { Console.WriteLine("WIN"); }
        else { Console.WriteLine("LOSE"); }
    }

    bool DFS(int i, int j, int turns)
    {
        if (board[i][j] == 'A') { return true; }
        if (i - turns >= 0 && board[i - turns][j] == 'S') { return false; }
        if (turns >= 8) { return true; }

        for (int di = -1; di <= 0; di++)
        {
            for (int dj = 1; dj >= -1; dj--)
            {
                int ni = i + dj, nj = j + dj;
                if (ni >= 0 && ni < 8 && nj >= 0 && nj < 8)
                {
                    if (ni - turns >= 0 && board[ni - turns][nj] == 'S') { continue; }
                    if (DFS(ni, nj, turns + 1)) { return true; }
                }
            }
        }
        return false;
    }
}


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

namespace CodeForces
{
    class Tokenizer
    {
        int pos;
        string[] tokens;
        TextReader reader;

        public Tokenizer(TextReader reader)
        {
            pos = 0;
            tokens = new string[] { };
            this.reader = reader;
        }

        public string NextToken()
        {
            if (pos == tokens.Length)
            {
                tokens = reader.ReadLine().Split(' ');
                pos = 0;
            }
            return tokens [pos++];
        }

        public int NextInt()
        {
            return int.Parse(NextToken());
        }
    }

    class MainClass
    {
        static Tokenizer t;
        static TextWriter w;

        public static void Init()
        {
            t = new Tokenizer(Console.In);
            w = Console.Out;
            //t = new Tokenizer(File.OpenText(@"../../in.txt"));
            //w = File.CreateText(@"../../out.txt");
        }

        public static void Main(string[] args)
        {
            Init();
            int n = t.NextInt();
            List<int>[] c = new List<int>[4];
            for (int i = 0; i < 4; i++)
                c [i] = new List<int>();
            for (int i = 1; i <= n; i++)
                c [t.NextInt()].Add(i);

            List<int>[] dep = new List<int>[n + 1];
            for (int i = 1; i <= n; i++)
            {
                dep [i] = new List<int>();
                int k = t.NextInt();
                for (int j = 0; j < k; j++)
                    dep [i].Add(t.NextInt());
            }

            int cost = int.MaxValue;
            for (int start = 1; start <= 3; start++)
            {
                bool[] done = new bool[n + 1];
                int cur = start;
                int rem = n;
                int curCost = 0;
                while (rem > 0)
                {
                    for (int j = 0; j < c[cur].Count; j++)
                    {
                        foreach (var a in c[cur])
                        {
                            if (done [a])
                                continue;
                            bool ready = true;
                            foreach (var b in dep[a])
                                if (!done [b])
                                    ready = false;
                            if (ready)
                            {
                                done [a] = true;
                                rem--;
                            }
                        }
                    }
                    cur++;
                    if (cur == 4)
                        cur = 1;
                    if (rem > 0)
                        curCost++;
                }

                cost = Math.Min(cost, curCost);
            }

            cost += n;
            w.WriteLine(cost);
            w.Close();
        }
    }
}


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

namespace CodeForces
{
    class Tokenizer
    {
        int pos;
        string[] tokens;
        TextReader reader;

        public Tokenizer(TextReader reader)
        {
            pos = 0;
            tokens = new string[] { };
            this.reader = reader;
        }

        public string NextToken()
        {
            if (pos == tokens.Length)
            {
                tokens = reader.ReadLine().Split(' ');
                pos = 0;
            }
            return tokens [pos++];
        }

        public int NextInt()
        {
            return int.Parse(NextToken());
        }
    }

    class MainClass
    {
        static Tokenizer t;
        static TextWriter w;

        public static void Init()
        {
            t = new Tokenizer(Console.In);
            w = Console.Out;
            t = new Tokenizer(File.OpenText(@"../../in.txt"));
            //w = File.CreateText(@"../../out.txt");
        }

        public static void Main(string[] args)
        {
            Init();
            int n = t.NextInt();

            int[] machine = new int[n + 1];
            int[] inDegree = new int[n + 1];

            for (int i = 1; i <= n; i++)
                machine [i] = t.NextInt();

            var a = new List<int>[n + 1];
            for (int i = 1; i <= n; i++)
                a [i] = new List<int>();

            for (int i = 1; i <= n; i++)
            {
                int k = t.NextInt();
                inDegree [i] = k;
                while (k-- > 0)
                {
                    a [t.NextInt()].Add(i);
                }
            }

            int cost = int.MaxValue;
            for (int start = 1; start <= 3; start++)
            {
                int curCost = n;
                int[] curInDegree = (int[])inDegree.Clone();
                var q = new Queue<int>[4];
                for (int i = 1; i <= 3; i++)
                    q [i] = new Queue<int>();
                int rem = n;
                for (int i = 1; i <= n; i++)
                    if (inDegree [i] == 0)
                        q [machine [i]].Enqueue(i);
                int curMachine = start;
                while (true)
                {
                    while (q[curMachine].Count != 0)
                    {
                        int curJob = q [curMachine].Dequeue();
                        foreach (var job in a[curJob])
                        {
                            curInDegree [job]--;
                            if (curInDegree [job] == 0)
                                q [machine [job]].Enqueue(job);
                        }
                        rem--;
                    }
                    if (rem == 0)
                        break;

                    curCost++;
                    curMachine++;
                    if (curMachine == 4)
                        curMachine = 1;
                }
                cost = Math.Min(cost, curCost);

            }

            w.WriteLine(cost);
        }
    }
}


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

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


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

namespace CodeForces._265
{
    PUBLIC class ProblemA
    {
        public static void Main(string[]  varg)
        {
            int n = int.Parse(System.Console.ReadLine());
            string s = System.Console.ReadLine();

            int rv = 0;
            foreach(var c in s)
            {
                rv++;
                if (c == '0')
                    break;
            }
            System.Console.WriteLine(rv);
        }
    }
}


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

namespace CodeForces
{
    class B
    {
        static void Main(string[] args)
        {
           int n = int.Parse(Console.ReadLine());
           int[] a = new int[2*n];
           string[] token = Console.ReadLine().Split();
           for(int i=0;i<2*n;i++)
           {
              a[i] = int.Parse(token[i]);
           }
           Array.Sort(a);
           int num = 0;
           for(int i=0;i<2*(n-1);i+=2){
              int val  = a[i+1] - a[i];

              num += val;
           }
           Console.WriteLine(num);
        }
    }
}


using System;
namespace Whatever {

    class asearch {

        static int N;
        static int numCount;
        static int[] an = new int[2000];

        static void ReadData() {
            Int32.TryParse(Console.ReadLine(), out N);

            var line = Console.ReadLine().Split(new char[]{' '});

            numCount = line.Length;
            for (int i = 1; i <= numCount; ++i)
            {
                Int32.TryParse(line[i-1], out an[i]);
            }
        }

        // BWBWBWBW
        // 101010101  mod 2
        static int NextLoc(int start, int color) {
            if (start % 2 == color) {
                return start;
            } else {
                return start+1;
            }
        }

        static int TrySolve(int color) {
            var poop = new boolean[10000];
            var solved = new boolean[10000];
            for (int i = 1; i<=numCount; ++i) {
                if (a[i] %2 == color) {
                    poop[a[i]] =true;
                    solved[i] = true;
                } else {
                    solved[i] =false;
                }
            }

            var result = 0;

            for (int i = 1; i<=numCount; ++i) {
                if (!solved[i]) {
                    var plc = -1;
                    var plcDis = 10101010;
                    for (int j = 1; j<=N; ++j) {
                        if (!poop[j] && Math.Abs(j-a[i]) < plcDis) {
                            plcDis = Math.Abs(j-a[i]);
                            plc = j;
                        }
                    }
                    poop[j] = true;
                    solved[i] = true;
                    result += Math.Abs(j-a[i]);
                }
            }

            return result;

        }

        static void Main(string[] args) {

            ReadData();
            var minMoves = 2147483600;
            var tmp = TrySolve(0);
            if (tmp != -1 && tmp < minMoves) {
                minMoves = tmp;
            }
             tmp = TrySolve(1);
            if (tmp !=-1 && tmp < minMoves) {
                minMoves = tmp;
            }
            Console.WriteLine(minMoves);
            //Console.WriteLine(Console.ReadLine());
        }

    }
}


using System;
using System.Collections.Generic;
namespace Whatever {

    class abfs {

        static int N;
        static int numCount;
        static int[] an = new int[2000];

        struct State {
            public bool[] poop;

            public bool isSolved() {
                bool c0=false, c1=false;
                for (int i = 1; i<=N;++i) {
                    if (i%2 == 0 && poop[i]) {
                        c0 = true;
                    }
                    if (i%2==1&&poop[i]){
                        c1 = true;
                    }
                    if (c1&&c0) return false;
                }
                return true;
            }

            public int depth;

            public int hash() {
                int result = 0;
                for (int i = 1; i<=N; ++i) {
                    if (poop[i]) {
                        result += (1<< (i-1));
                    }
                }
                return result;
            }
        }

        static void ReadData() {
            Int32.TryParse(Console.ReadLine(), out N);

            var line = Console.ReadLine().Split(new char[]{' '});

            numCount = line.Length;
            for (int i = 1; i <= numCount; ++i)
            {
                Int32.TryParse(line[i-1], out an[i]);
            }
        }

        static int TrySolve(int color) {
            var q = new Queue<State>();
            var visited = new HashSet<int>();
            var tmp = new State();
            tmp.poop = new bool[101];
            for (int i = 1;i<=numCount; ++i) {
                tmp.poop[an[i]] = true;
            }

            q.Enqueue(tmp);
            visited.Add(tmp.hash());// = true;
            tmp.depth = 0;
            while (q.Count > 0) {
                var head = q.Dequeue();
                if (head.isSolved()) {
                    return head.depth;
                }
                for (int i = 1; i<=N;++i) {
                    if (head.poop[i] && i<N
                    && !head.poop[i+1]) {
                        var newP = (bool[])head.poop.Clone();
                        newP[i+1] = true;
                        newP[i] = false;
                        var newState = new State();
                        newState.poop = newP;
                        newState.depth = head.depth +1;
                        if (!visited.Contains(newState.hash())) {
                            visited.Add(newState.hash());//] = true;
                            q.Enqueue(newState);
                        }
                    }
                     if (head.poop[i] && i>1
                    && !head.poop[i-1]) {
                        var newP = (bool[])head.poop.Clone();
                        newP[i-1] = true;
                        newP[i] = false;
                        var newState = new State();
                        newState.poop = newP;
                        newState.depth = head.depth+1;
                        if (!visited.Contains(newState.hash())) {
                            visited.Add(newState.hash());// = true;
                            q.Enqueue(newState);
                        }
                    }

                }
            }

            return -1;

        }

        static void Main(string[] args) {

            ReadData();
            var minMoves = 2147483600;
            var tmp = TrySolve(0);
            if (tmp != -1 && tmp < minMoves) {
                minMoves = tmp;
            }
             tmp = TrySolve(1);
            if (tmp !=-1 && tmp < minMoves) {
                minMoves = tmp;
            }
            Console.WriteLine(minMoves);
            //Console.WriteLine(Console.ReadLine());
        }

    }
}


using System;

public sealed class Program {

  const Int64 Mod = 1000000007;

  static void Add(ref Int64 cur, Int64 add) {
    cur = (cur + add) % Mod;
  }

  public Program () {
    Int32 n = ReadInt(), cap = ReadInt(), i, cnt50 = 0, cnt100 = 0, a, b, c, d;
    for (i = 0; i < n; ++i) {
      if (ReadInt() == 50) {
        ++cnt50;
      } else {
        ++cnt100;
      }
    }
    Int64[,] binomial = new Int64[n + 1, n + 1];
    for (i = 0; i <= n; ++i) {
      binomial[i, 0] = binomial[i, i] = 1;
    }
    for (a = 2; a <= n; ++a) {
      for (b = 1; b < a; ++b) {
        binomial[a, b] = (binomial[a - 1, b] + binomial[a - 1, b - 1]) % Mod;
      }
    }
    Int64[, ,] dp = new Int64[n * 2 + 1, cnt50 + 1, cnt100 + 1];
    dp[0, cnt50, cnt100] = 1;
    for (i = 0; ; ++i) {
      if (i == n * 2) {
        Console.WriteLine(-1);
        Console.WriteLine('0');
      } else if (i % 2 != 0 && dp[i, cnt50, cnt100] != 0) {
        Console.WriteLine(i);
        Console.WriteLine(dp[i, cnt50, cnt100])
      }
      for (a = 0; a <= cnt50; ++a) {
        for (b = 0; b <= cnt100; ++b) {
          if (dp[i, a, b] != 0) {
            for (c = 0; c <= a; ++c) {
              for (d = 0; d <= b && c * 50 + d * 100 <= cap; ++d) {
                if (c + d != 0) {
                  Add(ref dp[i + 1, cnt50 - (a - c), cnt100 - (b - d)], dp[i, a, b] * binomial[a, c] % Mod * binomial[b, d] % Mod);
                }
              }
            }
          }
        }
      }
    }
  }

  // stuff cutline

  public static void Main() {
#if DEBUG
    Console.SetIn(new System.IO.StreamReader("..\\..\\in.txt"));
#endif
    var root = new Program();
    Console.Out.Flush();
  }

  static Int32 ReadInt() {
    Boolean neg = false;
    Int32 ch, ans = 0;
    do {
      ch = Console.Read();
      neg |= ch == (Int32)'-';
    } while (!Char.IsDigit((Char)ch));
    do {
      ans = ans * 10 + (ch & 0xf);
      ch = Console.Read();
    } while (Char.IsDigit((Char)ch));
    return neg ? -ans : ans;
  }

  static Int32[] ReadArray() {
    return Array.ConvertAll<String, Int32>(Console.ReadLine().Split(), Int32.Parse);
  }

}


using System;

public sealed class Program {

  const Int64 Mod = 1000000007;

  static void Add(ref Int64 cur, Int64 add) {
    cur = (cur + add) % Mod;
  }

  public Program () {
    Int32 n = ReadInt(), cap = ReadInt(), i, cnt50 = 0, cnt100 = 0, a, b, c, d;
    for (i = 0; i < n; ++i) {
      if (ReadInt() == 50) {
        ++cnt50;
      } else {
        ++cnt100;
      }
    }
    Int64[,] binomial = new Int64[n + 1, n + 1];
    for (i = 0; i <= n; ++i) {
      binomial[i, 0] = binomial[i, i] = 1;
    }
    for (a = 2; a <= n; ++a) {
      for (b = 1; b < a; ++b) {
        binomial[a, b] = (binomial[a - 1, b] + binomial[a - 1, b - 1]) % Mod;
      }
    }
    Int64[, ,] dp = new Int64[n * 2 + 1, cnt50 + 1, cnt100 + 1];
    dp[0, cnt50, cnt100] = 1;
    for (i = 0; ; ++i) {
      if (i == n * 2) {
        Console.WriteLine(-1);
        Console.WriteLine('0');
      } else if (i % 2 != 0 && dp[i, cnt50, cnt100] != 0) {
        Console.WriteLine(i);
        Console.WriteLine(dp[i, cnt50, cnt100]);
      }
      for (a = 0; a <= cnt50; ++a) {
        for (b = 0; b <= cnt100; ++b) {
          if (dp[i, a, b] != 0) {
            for (c = 0; c <= a; ++c) {
              for (d = 0; d <= b && c * 50 + d * 100 <= cap; ++d) {
                if (c + d != 0) {
                  Add(ref dp[i + 1, cnt50 - (a - c), cnt100 - (b - d)], dp[i, a, b] * binomial[a, c] % Mod * binomial[b, d] % Mod);
                }
              }
            }
          }
        }
      }
    }
  }

  // stuff cutline

  public static void Main() {
#if DEBUG
    Console.SetIn(new System.IO.StreamReader("..\\..\\in.txt"));
#endif
    var root = new Program();
    Console.Out.Flush();
  }

  static Int32 ReadInt() {
    Boolean neg = false;
    Int32 ch, ans = 0;
    do {
      ch = Console.Read();
      neg |= ch == (Int32)'-';
    } while (!Char.IsDigit((Char)ch));
    do {
      ans = ans * 10 + (ch & 0xf);
      ch = Console.Read();
    } while (Char.IsDigit((Char)ch));
    return neg ? -ans : ans;
  }

  static Int32[] ReadArray() {
    return Array.ConvertAll<String, Int32>(Console.ReadLine().Split(), Int32.Parse);
  }

}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace _307b
{
    class Program
    {
        const string _inputFilename = "";
        const string _outputFilename = "";

        static void Main(string[] args)
        {

            var outputWriter = new StreamWriter(Console.OpenStandardOutput(), Encoding.Default, 1024 * 1024);

#if DEBUG
            Console.SetIn(getInput());
#else
            if (!string.IsNullOrEmpty(_inputFilename))
            {
                var inputStream = new FileStream(_inputFilename, FileMode.Open);
                outputWriter = new StreamWriter(_outputFilename, true, Encoding.Default, 1024 * 1024);

                Console.SetIn(File.OpenText(_inputFilename));
            }
#endif
            Console.SetOut(outputWriter);

            try
            {
                solution();
            }
            finally
            {
                outputWriter.Close();
            }
        }

        static void solution()
        {
            #region SOLUTION
            var a = Console.ReadLine();
            var b = Console.ReadLine();
            var c = Console.ReadLine();

            var ac = new int[26];
            var bn = new int[26];
            var cn = new int[26];

            for (int i = 0; i < a.Length; i++)
            {
                // 97
                var next = ((int)a[i]) - 97;
                ac[next]++;
            }

            for (int i = 0; i < b.Length; i++)
            {
                var next = ((int)b[i]) - 97;
                bn[next]++;
            }

            for (int i = 0; i < c.Length; i++)
            {
                var next = ((int)c[i]) - 97;
                cn[next]++;
            }

            var maxb = 0;
            var maxc = 0;
            var max = 0;
            var temp = new int[26];
            for (int i = 0; i < a.Length; i++)
            {
                var can = i * b.Length <= a.Length;
                if (!can)
                {
                    break;
                }

                for (int j = 0; j < 26; j++)
                {
                    temp[j] = ac[j] - i * bn[j];

                    if (temp[j] < 0)
                    {
                        can = false;
                        break;
                    }
                }

                if (!can)
                {
                    continue;
                }

                var cc = int.MaxValue;
                for (int j = 0; j < 26; j++)
                {
                    if (cn[j] != 0)
                    {
                        cc = Math.Min(cc, temp[j] / cn[j]);
                    }
                }

                if (cc + i > max)
                {
                    max = cc + i;
                    maxb = i;
                    maxc = cc;
                }
            }

            if (max == 0)
            {
                Console.WriteLine(a);
                return;
            }
            else
            {
                var gcan = false;
                var bcount = maxb;
                var ccount = maxc;

                for (int j = 0; j < 26; j++)
                {
                    ac[j] -= bn[j] * bcount + cn[j] * ccount;
                }

                var sb = new StringBuilder();
                for (int i = 0; i < bcount; i++)
                {
                    sb.Append(b);
                }

                for (int i = 0; i < ccount; i++)
                {
                    sb.Append(c);
                }

                for (int i = 0; i < 26; i++)
                {
                    for (int j = 0; j < ac[i]; j++)
                    {
                        sb.Append(((char)(i + 97)));
                    }
                }

                Console.WriteLine(sb.ToString());
            }

            //var l = 0;
            //var r = a.Length;
            //while (true)
            //{
            //    if (l == r)
            //    {
            //        break;
            //    }

            //    var mid = l + (r - l + 1) / 2;

            //    var gcan = false;
            //    for (int i = 0; i < mid + 1; i++)
            //    {
            //        var bcount = i;
            //        var ccount = mid - i;
            //        var can = true;
            //        for (int j = 0; j < 26; j++)
            //        {
            //            if (ac[j] - bn[j] * bcount - cn[j] * ccount < 0)
            //            {
            //                can = false;
            //                break;
            //            }
            //        }

            //        if (can)
            //        {
            //            gcan = true;
            //            break;
            //        }
            //    }

            //    if (gcan)
            //    {
            //        l = mid;
            //    }
            //    else
            //    {
            //        r = mid - 1;
            //    }
            //}

            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


	using System;

	namespace Project_1
	{
		class MainClass
		{
			public static void Main(string[] args)
			{
				/*	string s;
					s = Console.ReadLine();
					string str = "hello";
					Console.WriteLine(str[0]+s);
					Console.WriteLine(Calc(3, 5));*/
				//Вводим начальные данные
				int el_count=0;//количество предметов
				int min_weight=0, max_weight=0;//минимальный и максимальный вес предметов
			int min_element=0,max_element = 0;//минимальный и максимальный вес предметов в наборе
				int diff = 0;//минимальная разница в весе между минимальным и максимальным предметами в наборе
				int count = 0;//количество возможных комбинаций
			String str,substr="1";
			//	Console.Write("Введите количество предметов: ");
				el_count = Int32.Parse(Console.ReadLine());
		//		Console.Write("Введите минимальный общий вес: ");
				min_weight = Int32.Parse(Console.ReadLine());
		//		Console.Write("Введите максимальный общий вес: ");
				max_weight = Int32.Parse(Console.ReadLine());
		//		Console.Write("Введите минимальную разницу в весе м/у самым легким и самым тяжелым предметами: ");
				diff = Int32.Parse(Console.ReadLine());
				int[] mas = new int[el_count];

                string[] lines1 = Console.ReadLine().Split(' ');

		//		Console.WriteLine("Заполните веса предметов");
				for (int i = 0; i < mas.Length; i++)
				{
			//		Console.Write("вес предмета № {0}: ",i+1);
					mas[i] = Int32.Parse(lines1[i]/*Console.ReadLine()*/);
				}
				// сортировка
				int temp=0;
				for (int i = 0; i < mas.Length - 1; i++)
				{
					for (int j = i + 1; j < mas.Length; j++)
					{
						if (mas[i] > mas[j])
						{
							temp = mas[i];
							mas[i] = mas[j];
							mas[j] = temp;
						}
					}
				}
				// вывод
				/*Console.WriteLine("Вывод отсортированного массива");
				for (int i = 0; i < mas.Length; i++)
				{
					Console.WriteLine(mas[i]);
				}*/
				//Console.ReadLine();
			temp = 0;
			for (int i = 0; i < Math.Pow(2,mas.Length); i++)
				{
					str = Convert.ToString(i, 2);
					while (str.Length < mas.Length)
						{
							str = "0" + str;
						}
				//в переменной str хранятся все возможные комбинации предметов в формате 0/1
				min_element = 0;
				max_element = 0;
				temp = 0;
				for (int j = 0; j < mas.Length; j++)
				{

					if (Convert.ToString(str[j]) == "1")
					{
						if (min_element == 0)
						{
							min_element = mas[j];
						}
						if (max_element == 0)
						{
							max_element = mas[j];
						}
						if (min_element > mas[j])
						{
							min_element = mas[j];
						}
						if (max_element < mas[j])
						{
							max_element = mas[j];
						}
						temp += mas[j];
					}
				}
				if ((max_element - min_element) >= diff && temp >= min_weight && temp <= max_weight)
				{
					count++;
				}
				//Console.WriteLine(str);
				}

			Console.WriteLine(/*"Количество возможных комбинаций: "+*/Convert.ToString(count));
			}
			static int Calc(int a, int b)
			{
				return a + b;
			}
		}
	}


program Project3;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Math;

var
  inStr: string;
  n, i, ii, MaxCombinations, dv,j: Integer;
  m, k, p, TotalWeigth, MinWeigth, MaxWeigth, PacksCount: Integer;
  Goods: array of Integer;
  TempGoods:array of Integer;

function ExtractNextNum(s: string):string;
begin
  Result := Copy(inStr,1,Pos(' ', inStr)-1);
  Delete(inStr,1,Pos(' ', inStr));
end;

begin
  Readln(inStr);
  inStr := inStr + ' ';
  n := StrToInt(ExtractNextNum(inStr));
  m := StrToInt(ExtractNextNum(inStr));
  k := StrToInt(ExtractNextNum(inStr));
  p := StrToInt(ExtractNextNum(inStr));

  Readln(inStr);
  inStr := inStr + ' ';
  SetLength(Goods, n);
  for i:=0 to n-1 do
    begin
      Goods[i]:= StrToInt(ExtractNextNum(inStr));
    end;

  PacksCount:=0;

  MaxCombinations := Trunc(Power(2, n));// - 1; //всего вариантов получить различные наборы товаров

  for i:=1 to MaxCombinations do //
    begin
      SetLength(TempGoods,0);
      //заполняем массив следующей комбинацией товаров
      //используем i как двоичную маску отбора элементов в массиве товаров
 //  for ii:=0 to n-1 do
    dv:=i;
	ii:=0 ;
	while (dv>0) do
	begin
	      if((dv mod 2)=1) then

      //   if ( (i and Trunc(Power(2,ii))) = (Trunc(Power(2,ii))) ) then
		  begin
		     SetLength(TempGoods,Length(TempGoods)+1);
             TempGoods[Length(TempGoods)-1]:=Goods[ii];
            end;
		     dv := dv div 2;
			 ii:=ii+1;
        end;

      if Length(TempGoods)<2 then Continue;//набор из 1 товара сразу нет

      TotalWeigth := 0;
      MinWeigth:=TempGoods[0];
      MaxWeigth:=TempGoods[0];

      for ii:=0 to Length(TempGoods)-1 do
       begin
         TotalWeigth:=TotalWeigth + TempGoods[ii];
         if MinWeigth > TempGoods[ii] then MinWeigth:= TempGoods[ii];
         if MaxWeigth < TempGoods[ii] then MaxWeigth:= TempGoods[ii];
       end;

      if ((TotalWeigth < m) or (TotalWeigth > k)) then Continue; //условие суммарного веса
      if ((MaxWeigth - MinWeigth) < p) then Continue;  //условие разницы крайних весов

      Inc(PacksCount);//условия подошли - берем как вариант пачки товаров

     end;

  Writeln(inttostr(PacksCount));
 // readln;

end.


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

namespace CodeforcesICPC
{
   class MadOver
   {
      static void Main(string[] args)
      {
         string[] token = Console.ReadLine().Split();
         string[] token2 = Console.ReadLine().Split();

         int x1 = int.Parse(token[0]) + 100;
         int y1 = int.Parse(token[1]) + 100;

         int x2 = int.Parse(token2[0]) + 100;
         int y2 = int.Parse(token2[1]) + 100;

        if(x1==x2){x-=1}
        if(y1==y2){y-=1}

         Console.WriteLine( Math.Abs(x2-x1)*2 + Math.Abs((y1+1)-x1)*2);
      }
   }

}


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

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] x1, x2;
            int e1;
            x1=Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            x2=Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            if (x1[0] == x2[0])
            {
                e1 = 2*(Math.Abs(x1[1] - x2[1])) + 6;
            }
            else
            {
                if (x1[1] == x2[1])
                {
                    e1 = 2*(Math.Abs(x1[0] - x2[0])) + 4;
                }
                else
                {
                    e1 = 2 * (Math.Abs(x1[0] - x2[0]) + Math.Abs(x1[1] - x2[1])) + 4;
                }
            }
            Console.WriteLine(e1);

        }
    }
}


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string st = Console.ReadLine();
            bool left, right, down, up;
            left = right = down = up = true;
            if (st.Contains("1") || st.Contains("4") || st.Contains("7") || st.Contains("0"))
            {
                left = false;
            }
            if (st.Contains("3") || st.Contains("6") || st.Contains("9") || st.Contains("0"))
            {
                right = false;
            }
            if (st.Contains("1") || st.Contains("2") || st.Contains("3"))
            {
                up = false;
            }
            if (st.Contains("7") || st.Contains("0") || st.Contains("9"))
            {
                down = false;
            }
            if (left || right || down || up)
            {
                Console.WriteLine("NO");
            }
            else
            {
                Console.WriteLine("YES");
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
class Solution
{

  static void Main(String[] args)
  {
    string[] valid = new string[8] {
      "0000000",
      "0000000",
      "0011100",
      "0011100",
      "0011100",
      "0001000",
      "0000000",
      "0000000"
    };
    int[] row = new int[] {5,2,2,2,3,3,3,4,4,4};
    int[] col = new int[] {3,2,3,4,2,3,4,2,3,4};

    int count = int.Parse(Console.ReadLine());
    string digits = Console.ReadLine();
    bool found = false;
    for (int i = 0; i < 10; ++i)
    {
      bool v = true;
      int idx = (int)digits[0]-(int)'0';
      int or = row[idx]-row[i];
      int oc = col[idx]-col[i];
      if (or == 0 && oc == 0)
      {
        continue;
      }
      for (int j = 0; j < count; ++j)
      {
        idx = (int)digits[j]-(int)'0';
        int ir = row[idx] - or;
        int ic = col[idx] - oc;
        if (valid[ir][ic] == '0')
        {
          v = false;
          break;
        }
      }
      if (v)
      {
        found = true;
        break;
      }
    }
    if (found)
    {
      Console.WriteLine("NO");
    }
    else
    {
      Console.WriteLine("YES");
    }
  }
}


using System; using System.Linq;

class Program {
  static void Main() {
    var f = Enumerable.Range(0,3).Select(i => Console.ReadLine().Split(' ').Select(int.Parse).Select(x => x % 2).ToArray()).ToArray();
    var ff = new int[3,3];
    for (var y = 0 ; y < 3 ; y++) for (var x = 0 ; x < 3 ; x++)
      for (var yi = y-1 ; yi <= y+1 ; yi++) for (var xi = x-1 ; xi <= x+i ; xi++)
        if (yi >= 0 && xi >= 0 && f[y][x] == 1 && yi < 3 && xi < 3)
          ff[yi,xi] = 1 ^ ff[yi,xi];
    for (var y = 0 ; y < 3; y++) {
      for (var x = 0; x < 3 ; x++) Console.Write("{0} ", ff[y,x]);
      Console.WriteLine();
    }
  }
}


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
           // Console.ReadLine();
            Console.ReadLine();
            string Data = Console.ReadLine().Replace("0", "");
            if (Data.Length == 0) { Console.WriteLine("YES"); return; }
            int[] arr = new int[Data.Length];
            int[] sign = new int[Data.Length];
            #region proccess1

            while (true)
            {
                arr[0]++;
                if (arr[0] >= Data.Length - 1) // refer to first counter max
                {
                    for (int i = 0; i < arr.Length - 1; i++) //
                    {
                        if (arr[i] >= Data.Length  - i & arr[i + 1] != Data.Length - i - 1)
                        {
                            arr[i + 1]++;
                            for (int j = i; j >= 0; j--)
                            {
                                arr[j] = arr[j + 1] + 1;
                            }
                        }
                    }
                }
            #endregion

            #region proccess2
                if (arr[arr.Length - 1] == 1) { Console.WriteLine("NO"); return; }
                int C = 0;
                for (int i = arr.Length - 1; i >= 0; i--)
                {
                    if (arr[i] > 0)
                    {
                        string S = Data.Substring(arr[i + 1], (arr[i] - arr[i + 1]));
                        if (C == 0) C = ____(S);
                        else if (C != ____(S))
                        {
                            continue;
                        }
                    }
                    if (i == 0)
                    {
                        string S = Data.Substring(arr[0], (Data.Length - arr[0]));
                        if (S.Length > 0) if (C == ____(S)) { Console.WriteLine("YES"); return; };
                    }
                }
                #endregion
            }

        }
        static int ____(string num)
        {
            int n = num.Length;
            int x = int.Parse(num);
            int A = 0;
            for (int i = 0; i < n; i++)
            {
                A += x % 10;
                x /= 10;
            }
            return A;
        }
    }
}


using System;
 class Program
    {
        static void Main(string[] args)
        {
            int sum=0;
            int[] data;
            {
                string input = Console.In.ReadToEnd().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)[1];
                data = new int[input.Length];
                for (int i = 0; i < input.Length;)
                    sum += data[i] = input[i++]-48;
            }
            int[] dividers = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 };
            for(int i = 0, l; data.Length>=dividers[i]; i++)
            {
                if(sum%dividers[i]==0)
                {
                    l = sum / dividers[i];
                    int sm = 0;
                    for (int j = 0; j < data.Length;)
                    {
                        if (sm < l) sm += data[j++];
                        else if (sm > l) break;
                        else { dividers[i]--; sm = 0; }
                    }
                    if(dividers[i]==1 && sm==l) { sum = int.MinValue; break; }
                }
            }
            Console.WriteLine(sum < 0 ? "YES" : "NO");
        }
    }


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CupC", "CupC\CupC.csproj", "{DF7C8BA3-F7C7-4D00-8598-D385D38C8645}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{DF7C8BA3-F7C7-4D00-8598-D385D38C8645}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{DF7C8BA3-F7C7-4D00-8598-D385D38C8645}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{DF7C8BA3-F7C7-4D00-8598-D385D38C8645}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{DF7C8BA3-F7C7-4D00-8598-D385D38C8645}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal


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(' ');
             string[]yq=Console.ReadLine().Split(' ');
             string[]yqq=Console.ReadLine().Split(' ');
             int a=int.Parse(y[0]);
             int b=int.Parse(y[1]);
             int c=int.Parse(yq[0]);
             int d=int.Parse(yq[1]);
             int e=int.Parse(yqq[0]);
             int f=int.Parse(yqq[1]);
             int mass=0;
             for(int i=b+1;i>0;i--)
             {
                  mass+=i;
                  if(i==d)
                  mass-=c;
                  if(i==f)
                  mass-=e;
                  if(mass<0)
             mass=0;

             }

             Console.WriteLine(mass);
        }
    }
}


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

namespace Runner
{
    class Program
    {
        static void Main(string[] args)
        {
            //AVLTree<int> avlTree = new AVLTree<int>(97,
            //    new AVLTree<int>(49,
            //        new AVLTree<int>(37),
            //        new AVLTree<int>(81)),
            //    new AVLTree<int>(917));

            //avlTree.Traverse();

            string[] firstLineArgs = Console.ReadLine().Split(new char[] { ' ' });
            string[] secondLineArgs = Console.ReadLine().Split(new char[] { ' ' });
            string[] thirdLineArgs = Console.ReadLine().Split(new char[] { ' ' });

            int w = int.Parse(firstLineArgs[0]);
            int h = int.Parse(firstLineArgs[1]);

            int u1 = int.Parse(secondLineArgs[0]);
            int d1 = int.Parse(secondLineArgs[1]);

            int u2 = int.Parse(thirdLineArgs[0]);
            int d2 = int.Parse(thirdLineArgs[1]);

            if (d1 == d2)
            {
                throw new Exception();
            }

            Console.WriteLine(PushSnowball(w, h, u1, d1, u2, d2));

        }

        public static int PushSnowball(int w, int h, int u1, int d1, int u2, int d2)
        {
            int snowballSize = w;

            for (int i = h; i > 0; i--)
            {
                snowballSize += i;

                if (i == d1)
                {
                    snowballSize -= u1;
                }
                else if (i == d2)
                {
                    snowballSize -= u2;
                }

                if (snowballSize < 0)
                {
                    snowballSize = 0;
                }
            }

            return snowballSize;
        }
    }
}


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

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            //Maior fração atual irredutível encontrada
            string fracaoAtual = "";

            //Resultado da soma dos termos da fração
            var n = Int32.Parse(Console.ReadLine());
            int a=0, b=0;

            //Verificar se o número é válido conforme descrito no problema
            if (n < 3 || n > 1000)
            {
                Console.WriteLine("Entrada Inválida");
                return;
            }

            /*declaração do denominador da fração e loop de variação, o denominador deve ser maior que o numerador,
            então o máximo de verificação para saída é a metade de n*/
            for (int denominador = n - 1; denominador > n / 2; denominador--)
            {
                //Declaração do numerador da fração
                int numerador = n - denominador;

                //Criação da validação de valores primos entre si
                var primosEntreSi = true;

                /*Loop de verificação de possíveis divisores comuns entre numerador e denominador*/
                for (int i = 2; i <= numerador; i++)
                {
                    /*se o resto da divisão do numerador e denominador pelo termo testado
                        for igual a 0 os termos não são primos entre si*/
                    if (numerador % i == 0 && denominador % i == 0)
                    {
                        primosEntreSi = false;
                        break;
                    }
                }

                //Se forem primos entre si, a fração atual se torna a maior fração irredutível encontrada
                if (primosEntreSi)
                    fracaoAtual = numerador + " " + denominador;
                if (numerador == 16 && denominador == 18)
                {
                    numerador--;
                    denominador++;
                }
                a = numerador;
                b = denominador;
            }

            //Retorna o resultado
            Console.WriteLine("{0} {1}",a,b);
        }
    }
}


double c1 = convert.todouble(Console.ReadLine());


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

namespace test2
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = Convert.ToInt32(Console.ReadLine());
            string valueStr = Console.ReadLine();
            Test(valueStr, num);
        }
        public static void Test(string valueStr, int num)
        {
            List<int> num1 = new List<int>();
            List<int> num2 = new List<int>();
            int indexOf = 0;
            string MidStr = "";
            do
            {
                int indexTwo = valueStr.IndexOf('(', indexOf);
                if (indexTwo == -1)
                {
                    indexTwo = num;
                }
                MidStr = valueStr.Substring(indexOf, indexTwo - indexOf);
                int indexThree = MidStr.IndexOf(')', 0);

                if (indexThree != -1)
                {
                    string MidStr2 = MidStr.Substring(0, indexThree);
                    insertNum(num2, MidStr2);
                    //indexOf = indexTwo + 1;
                    MidStr = MidStr.Substring(indexThree + 1);
                }
                insertNum(num1, MidStr);
                indexOf = indexTwo + 1;
                if (indexOf >= num)
                {
                    break;
                }
            } while (true);
            int[] nums = num1.ToArray();
            Array.Sort(nums);
            Console.WriteLine("{0} {1}", nums[num1.Count - 1], num2.Count);
        }
        public static void insertNum(List<int> num, string MidStr)
        {
            string[] value = MidStr.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in value)
            {
                num.Add(item.Length);
            }
        }
    }
}


using System;
using System.Linq;

class B723 {
    public static void Main() {
        var n = int.Parse(Console.ReadLine());
        var s = Console.ReadLine();
        var ss = s.Split('(', ')');
        int answer1 = 0, answer2 = 0;
        for (int i = 0; i < ss.Length; i += 2) {
            var opts = StringSplitOptions.RemoveEmptyEntries;
            var sss = ss[i].Split(new char[] { '_' }, opts);
            foreach (var j in sss)
                if (answer1 < j.Length) answer1 = j.Length;
        }
        for (int i = 1; i < ss.Length; i += 2) {
            var sss = ss[i].Split(new char[] { '_' }, opts);
            answer2 += sss.Length;
        }
        Console.WriteLine($"{answer1} {answer2}");
    }
}


using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            string p = Console.ReadLine();
            string a = Console.ReadLine();
            a = a.Trim('_');
            while (a.IndexOf("__") > 0) a = a.Remove(a.IndexOf("__"), 1);

            List<string> brakes = new List<string>();
            while (a.IndexOf('(') > 0)
            {
                int ind = a.IndexOf('(');
                brakes.Add(a.Substring(ind+ 1, a.IndexOf(')') - ind- 1));
                a = a.Remove(ind, a.IndexOf(')') - ind + 1);
                a = a.Insert(ind, "_");
            }
            while (a.IndexOf("__") > 0) a.Remove(a.IndexOf("__"), 1);

            string[] b = a.Split('_');

            int max = 0;
            for (int i = 0; i < b.Length; i++) if (b[i].Length > max) max = b[i].Length;

            int count = 0;
            foreach (var s in brakes)
            {
                string s2 = s.Trim('_');
                string[] ss = s2.Split('_');
                count += ss.Length;
            }
            Console.WriteLine(max + " " + count);
            //Console.ReadKey();
        }
    }
}