LuckyNumbers.cs

using System;

namespace LuckyNunmbers {
	class Program {
        static void Main(string[] args) {
            var line = Console.ReadLine();
            var num = new LuckyNumber(long.Parse(line));
            Console.WriteLine(num.GetSuperLucky());
        }
    }

    internal enum NumberType {
        Simple, Lucky, SuperLucky
    }

    internal class LuckyNumber {

        private long _number;
        private long _lucky;
        private long _superLucky;

        private const uint LUCKY1 = 4;
        private const uint LUCKY2 = 7;

        private char CLUCKY1;
        private char CLUCKY2;

        public LuckyNumber(long number) {
            _number = number;
            var numType = GetNumberType();

            CLUCKY1 = UintToChar(LUCKY1);
            CLUCKY2 = UintToChar(LUCKY2);

            switch (numType) {
                case NumberType.Lucky:
                    _lucky = _number;
                    break;
                case NumberType.SuperLucky:
                    _lucky = _number;
                    _superLucky = _number;
                    break;
            }
        }

        public long GetLucky() {
            if (_lucky != 0) return _lucky;

            var digits = _number.ToString().ToCharArray();

            if (digits.Length > 0) {
                var buff = new char[digits.Length];
                for(int i=0; i<digits.Length; i++) {
                    buff[i] = CLUCKY1;
                }

                int index = digits.Length - 1;
                while (long.Parse(new string(buff)) < _number && index >= 0) {
                    buff[index] = CLUCKY2;
                    index--;
                }

                _lucky = long.Parse(new string(buff));
                while (index < digits.Length - 1) {
                    index++;
                    buff[index] = CLUCKY1;

                    var p = long.Parse(new string(buff));
                    if (p > _number) _lucky = p;
                    else buff[index] = CLUCKY2;
                }

                if(_lucky < _number) {
                    var arr = new char[digits.Length + 1];
                    for (int i = 0; i < arr.Length; i++) arr[i] = CLUCKY1;
                    _lucky = long.Parse(new string(arr));
                }

                return _lucky;
            }
            return 0;
        }

        public long GetSuperLucky() {
            if (_superLucky != 0) return _superLucky;
            if (_lucky == 0) this.GetLucky();

            var num = _lucky.ToString();
            if (num.Length % 2 != 0) {
                var result = GetAbsoluteLucky(num.Length + 1);
                _superLucky = long.Parse(result);
            } else {
                var ch = ToSuperLucky(num.ToCharArray());
                _superLucky = long.Parse(new string(ch));
            }

            return _superLucky;
        }

        private string GetAbsoluteLucky(int len) {
            var right = string.Empty;
            var left = string.Empty;
            len /= 2;

            for (int i = 0; i < len; i++) {
                left += LUCKY1;
                right += LUCKY2;
            }
            return left + right;
        }

        private char[] ToSuperLucky(char[] input) {
            var diff = GetCharacterDiff(input);
            if (diff > 0) {
                Array.Reverse(input);
                var replaced = ReplaceNext(input, (uint)(diff / 2));
                Array.Reverse(replaced);
                return replaced;
            } else if (diff < 0) {
                try {
                    var replaced = ReplaceFirst(input, (uint)(Math.Abs(diff) / 2));
                    return replaced;
                } catch (IndexOutOfRangeException) {
                    return string.Format("4{0}7", GetAbsoluteLucky(input.Length)).ToCharArray();
                }
            } else return input;
        }

        private char[] ReplaceNext(char[] inp, uint depth, int move = 0) {
            int offset = move;
            for (int i = offset; i < inp.Length; i++) {
                move++;
                if (char.GetNumericValue(inp[i]) == LUCKY1) {
                    inp[i] = CLUCKY2;
                    break;
                }
            }
            depth--;

            if (depth > 0) return ReplaceNext(inp, depth, move);
            return inp;
        }

        /// <summary>
        /// Replaces LUCKY2 to LUCKY1
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">In case of bad input</exception>
        private char[] ReplaceFirst(char[] inp, uint depth) {
            int index = inp.Length - 1;

            //This will throw ArgumentOutOfRangeException
            //in case if input is only LUCKY2
            while (char.GetNumericValue(inp[index]) != LUCKY1) index--;
            inp[index] = CLUCKY2;

            //This will throw ArgumentOutOfRangeException
            //in case if we have bad pattern
            while (depth + 1 > 0) {
                index++;
                depth--;
                inp[index] = CLUCKY1;
            }
            return inp;
        }

        public NumberType GetNumberType() {
            return LuckyNumber.GetNumberType(_number);
        }

        public static NumberType GetNumberType(long number) {
            uint l1s = 0, l2s = 0;
            foreach(var ch in number.ToString()) {
                if (char.GetNumericValue(ch) == LUCKY1) l1s++;
                else if (char.GetNumericValue(ch) == LUCKY2) l2s++;
                else return NumberType.Simple;
            }

            return (l1s == l2s)? NumberType.SuperLucky : NumberType.Lucky;
        }

        //---------------------

        private int GetCharacterDiff(char[] input) {
            int l1s = 0, l2s = 0;
            foreach (var ch in input) {
                if (char.GetNumericValue(ch) == LUCKY1) l1s++;
                else if (char.GetNumericValue(ch) == LUCKY2) l2s++;
            }

            return l1s - l2s;
        }

        private static string Reverse(string s) {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }

        private static char UintToChar(uint inp) {
            return inp.ToString()[0];
        }
    }
}


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

namespace prog2
{
    class Program
    {
        static private int length;
        private static int c4, c7;
        private static int cur;
        private static StringBuilder o;
        private static string s;
        static bool perebor(int p)
        {
            if (p == length)
            {
                if ((c4 == c7) && (Convert.ToInt32(o.ToString()) < cur) && (Convert.ToInt32(o.ToString()) >= Convert.ToInt32(s)))
                {
                    cur = Convert.ToInt32(o.ToString());
                    return true;
                }
                return false;
            }
            bool r, r1;
            r = false;
            r1 = false;
                char c = o[p];
                if (c == '4') c4--;
                if (c == '7') c7--;
            c4++;
            o[p] = '4';
            perebor(p + 1);
            c4--;
            c7++;
            o[p] = '7';
            perebor(p + 1);
            c7--;
                if (c == '4') c4++;
                if (c == '7') c7++;
                o[p] = c;
                return (r || r1);

        }

        static void Main(string[] args)
        {
            s = Console.ReadLine();
            o = new StringBuilder();
            cur = int.MaxValue;
            length = s.Length;
            c4 = 0;
            c7 = 0;
            for (int i = 0; i < length;i++ )
            {
                if (s[i] == '4') c4++;
                if (s[i] == '7') c7++;
            }
            o.Append(s);
            if (!perebor(0))
            {
                o.Clear();
                o.Append('4');
                c4++;
                o.Append(s);
                length++;
                perebor(0);
            }
            Console.WriteLine(cur);
        }
    }
}


using System;
using System.Linq;

class P {
  static IEnumerable<long> GetNums() {
    for (var i = 0L ;  ; i++) {
      var c = i;
      var res = 0L; var mult = 1L;
      while (c > 0) {
        if (c > 2) {
          var o = (c - 1)%2 + 1;
          c -= o;
          res += mult * (o == 1 ? 4 : 7);
        } else {
          c--;
          res += mult * (c == 1 ? 4 : 7);
        }
        c /= 2;
        mult *= 10;
      }
      yield return res;
    }
  }

  public static void Main() {
    long n = long.Parse(Console.ReadLine());
    var res = GetNums().First(x => x >= n);
    Console.Write(res);
  }
}


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.31101.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication44", "ConsoleApplication44\ConsoleApplication44.csproj", "{B4EAC425-845A-4522-8968-894DBB9017C1}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{B4EAC425-845A-4522-8968-894DBB9017C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{B4EAC425-845A-4522-8968-894DBB9017C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{B4EAC425-845A-4522-8968-894DBB9017C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{B4EAC425-845A-4522-8968-894DBB9017C1}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal


namespace ConsoleApplication44
{
    class Program
    {
        static void Main(string[] args)
        {
            int countBlack = 0;
            int countwhite = 0;
            string x = Console.ReadLine();
            for (int i = 0; i < x.Length; i++)
            {

                    if (x[i] == 'q')
                        countBlack += 9;
                    else if (x[i ] == 'Q')
                        countwhite+=9;
                    else if (x[i ] == 'R')
                        countwhite+=5;
                    else if (x[i ] == 'r')
                        countBlack+=5;
                    else if (x[i] == 'b')
                        countBlack += 3;
                    else if (x[i ] == 'B')
                        countwhite += 3;
                    else if (x[i ] == 'n')
                        countBlack += 3;
                    else if (x[i ] == 'N')
                        countwhite += 3;
                    else if (x[i ] == 'p')
                        countBlack += 1;
                    else if (x[i ] == 'P')
                        countwhite += 1;

            }
                if (countBlack > countwhite)
                    Console.WriteLine("Black");
                else if (countBlack < countwhite)
                    Console.WriteLine("White");
                else
                    Console.WriteLine("Draw");
                Console.ReadLine();

        }
    }
}


int white=0;
            int black=0;
            for (int i = 0; i < 8; i++)
            {
                string a = Console.ReadLine();
                for (int j = 0; j < a.Length; j++)
                {
                    if (a[j] == 'q')
                        white = white + 9;
                    else if (a[j] == 'r')
                        white = white + 5;
                    else if (a[j] == 'b')
                        white = white + 3;
                    else if (a[j] == 'n')
                        white = white + 3;
                    else if (a[j] == 'p')
                        white = white + 1;
                    else if (a[j] == 'Q')
                        black = black + 9;
                    else if (a[j] == 'R')
                        black = black + 5;
                    else if (a[j] == 'B')
                        black = black + 3;
                    else if (a[j] == 'N')
                        black = black + 3;
                    else if (a[j] == 'P')
                        black = black + 1;
                }
            }
            if (white > black)
            {
                Console.WriteLine("Black");
            }

            else if (black > white)
            {
                Console.WriteLine("White");
            }

            else
            {
                Console.WriteLine("Draw");
            }


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

namespace LongPath
{
    public class Problem417A
    {
        public static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
            var c = input[0];
            var d = input[1];

            input = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
            var n = input[0];
            var m = input[1];

            var k = int.Parse(Console.ReadLine());

            var mainpp = c / n;

            var count = 0;
            var candidates = n * m - k;

            while (candidates > 0)
            {
                if (int(c / n) <= d)
                {
                    count += c;
                    candidates -= n;
                }
                else {
                    count += d;
                    candidates--;
                }
            }

            Console.WriteLine(count);
        }
    }
}


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

namespace A.Diagonal_Walking
{
    class Program
    {
        static void Main(string[] args)
        {
            string n = Console.ReadLine();
            string text = Console.ReadLine();
            for (int i = 0; i < n; i++)
            {
                text = text.Replace("RU", "D");

            text = text.Replace("UR", "D");

            }

            Console.WriteLine(text.Length);
        }
    }
}


class Program
    {
        static void Main(string[] args)
        {
            int length = int.Parse(Console.ReadLine());
            string sequence = Console.ReadLine();
            sequence = sequence.Replace("UR", "D");
            sequence = sequence.Replace("RU", "D");

            Console.WriteLine(sequence.Length);
            Console.ReadKey();

        }
    }


/*
 * User: ������
 * Date: 11.02.2016
 * Time: 11:49

A. ����������� ������������������
���������� ����������� ������������������ ����� �����: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5....
��� ������������������ ���������� ��������� �������: ������� �������� ����� 1, ����� ����� �� 1 �� 2,
����� ����� �� 1 �� 3, ����� ����� �� 1 �� 4 � ��� �����.
�������� ��������, ��� ��� ������������������ ����� �����, � �� ����.
��������, ����� 10 ������� ����������� � ���� ������������������ �� 55 ������� (�������� ���������� � �������).
������� �����, ����������� �� n-� �������, ���� ��������� ���������� � �������.
������� ������
� ������������ ������ ��������� ����� ����� n (1 <= n <= 10^14) � ������� �����, ������� ����� �����.
�������� ��������, ��� �������� ����� �� ���������� � 32-������ ���� ������.
��� ���������� ����� �� ������ ������������, ��������, ��� long long � ����� C++ ��� ��� long � ����� Java.
�������� ������
�������� n-� ������� ������������������ (�������� ���������� � �������).
������� ������
������� ������
3
�������� ������
2
������� ������
5
�������� ������
2
������� ������
10
�������� ������
4
������� ������
55
�������� ������
10
������� ������
56
�������� ������
1

 */

using System;

namespace Edu003A
{
	class Program
	{
		public static void Main(string[] args)
		{
			Int64 n = Int64.Parse (Console.ReadLine ());
			Int64 m = int.Parse (Console.ReadLine ());
			int [] a = new int [n];
			for ( int i=0; i < n; i++ )
				a [i] = int.Parse (Console.ReadLine ());

			Array.Sort (a);

			int k=0, m=0;
			for ( int j=n-1; k < b; j--, m++ )
				k += a [j];

			Console.WriteLine (m);

//			Console.ReadKey(true);
		}
	}
}


class Solution {
    static void Main(String[] args) {

        string[] l=Console.ReadLine().Split();
        int n= Convert.ToInt32(l[0]);
        int i = 0;
        int s = 0;
        while(i < n)
        {
            s = s + i + (i - s);
            i++;
        }
        Console.WriteLine(n - s + i);
    }
}


class Solution {
    static void Main(String[] args) {

        string[] l=Console.ReadLine().Split();
        int n= Convert.ToInt32(l[0]);
        int i = 1;
        int s = 0;
        while(i < n)
        {
            s = s + i + (i - s);
            i++;
        }
        Console.WriteLine(n - s + i);
    }
}


using System;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            int[] a = Console.ReadLine().Split().Select(int.Parse).ToArray();
            Array.Sort(a);
            int s = 0;
            for (int i = 0; i < n-2; i++)
            {
                if (a[i] + a[i + 1] = a[i + 2])
                {
                    Console.WriteLine("Yes");
                    s = 1;
                    break;
                }
            }
            if (s == 0)
            {
                Console.WriteLine("NO");
            }
        }
    }
}


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mahmoud and a Triangle", "Mahmoud and a Triangle\Mahmoud and a Triangle.csproj", "{56457C61-535C-41BE-A293-79821A8104C2}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{56457C61-535C-41BE-A293-79821A8104C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{56457C61-535C-41BE-A293-79821A8104C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{56457C61-535C-41BE-A293-79821A8104C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{56457C61-535C-41BE-A293-79821A8104C2}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal


// C# program to find if
// it is possible to form
// a triangle from array values
using System;

class GFG
{

	// Method prints possible
	// triangle when array values
	// are taken as sides
	static bool isPossibleTriangle(int []arr,
								int N)
	{
		// If number of elements
		// are less than 3, then
		// no triangle is possible
		if (N < 3)
			return false;

		// first sort the array
		Array.Sort(arr);

		// loop for all 3
		// consecutive triplets
		for (int i = 0; i < N - 2; i++)

			// If triplet satisfies triangle
			// condition, break
			if (arr[i] + arr[i + 1] > arr[i + 2])
				return true;

		return false;
	}

	// Driver Code
	static public void Main ()
	{
		var input = Console.ReadLine();
            int n = int.Parse(input),ct=0;
            var arr = Console.ReadLine().Split().Select((s) =>
  Convert.ToInt32(s)).ToArray();

		if(isPossibleTriangle(arr, N))
			Console.WriteLine("YES" );
		else
			Console.WriteLine("NO");
	}
}

// This code is contributed by vt_m.


using System;
class Program
    {
        static void Main(string[] args)
        {
            int[] frts, sec;
            {
                string[] input = Console.In.ReadToEnd().Split(new char[] { ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                int n = int.Parse(input[0]);
                frts = new int[n++];
                for (int i = 2, j = 0; i <= n; ++i, j++)
                 frts[j] = int.Parse(input[i]);
                sec = new int[input.Length - n++];
                for (int j = 0; n < input.Length; ++n, ++j)
                  sec[j] = int.Parse(input[n]);
            }
            Array.Sort(frts);
            int nm = int.MinValue;
            for(int i = 0; i<frts.Length; ++i)
             if(sec.Contains(frts[i]))
                { nm = i; break; }
            if (nm >= 0) Console.WriteLine(frts[nm]);
            else
            {
                nm = sec.Min();
                if (nm > frts[0]) Console.WriteLine("{0}{1}", frts[0], nm);
                else Console.WriteLine("{0}{1}", nm, frts[0]);
            }
        }
    }


using System;
using System.Collections.Generic;
//using System.Console;

namespace PrettyIntegers
{
    class Program
    {
        public static void Main(string[] args)
        {
            int n,m;
            n = Console.Read();
            m = Console.Read();
            List<int> N = new List<int>();
            List<int> M = new List<int>();

            for(int i = 0; i<n; i++)
            {
                N.Insert(Console.Read());
            }
            N.Sort();

            for(int i = 0; i<m; i++)
            {
                M.Insert(Console.Read());
            }

            //First check for the common Elements
            foreach (int i in N)
            {
                if(M.Contains(i))
                {
                    Console.WriteLine(i);
                    return;
                }
            }

            //Now do the other thing
            int OneTwo = N.Min()*10 + M.Min(), TwoOne = M.Min()*10 + N.Min();
            Console.WriteLine(Math.Min(OneTwo, TwoOne));
            Console.Read();
        }
    }
}using System;
using System.Collections.Generic;
//using System.Console;

namespace PrettyIntegers
{
    class Program
    {
        public static void Main(string[] args)
        {
            int n,m;
            string[] parts = Console.ReadLine().Split(' ');
            n = int.Parse(parts[0]);
            m = int.Parse(parts[1]);
            List<int> N = new List<int>();
            List<int> M = new List<int>();

            parts = Console.ReadLine().Split(' ');
            for(int i = 0; i<n; i++)
            {
                N.Add(int.Parse(parts[i]));
            }
            N.Sort();

            parts = Console.ReadLine().Split(' ');
            for(int i = 0; i<m; i++)
            {
                M.Add(int.Parse(parts[i]));
            }
            M.Sort();

            //First check for the common Elements

            foreach (int i in N)
            {
                if(M.Contains(i))
                {
                    Console.WriteLine(i);
                    return;
                }
            }

            //Now do the other thing
            int min1 = N[0];
            int min2 = M[0];
            int OneTwo = min1*10 + min2, TwoOne = min2*10 + min1;
            Console.WriteLine(Math.Min(OneTwo, TwoOne));
            //Console.Read();
        }
    }
}


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

namespace Suffix_Structures
{
    class Program
    {
        static bool chec(  string ss,  string tt)
        {
            char[] s =  ss.ToCharArray();
            char[] t = tt.ToCharArray();
            for (int i = 0; i < t.Count(); i++)
            {
                bool ddd = false;
                for (int c = 0; c < s.Count(); c++)
                {
                    if (t[i] == s[c])
                    { ddd = true;

                        s[c] = ',';

                        break; }
                }

                if (!ddd)
                {
                    return false;
                }
            }
            return true;
        }
        static void Main(string[] args)
        {
           // var bb = chec("arary", "array");

            Console.WriteLine(ss);
            string s, t;
            s = Console.ReadLine();

            t= Console.ReadLine();
            int cc, rr;
            cc = s.Count();
            rr = t.Count();
            if (chec(s,t)&&rr==cc)
            {
                Console.WriteLine("array"); return;
            }

            int column = 0,i;
            for (  i = 0; i < rr; i++)
            {
                while (column<cc && t[i]!=s[column])
                {
                    column++;
                }
                if (column==cc)
                {
                    break;
                }
            }
            if (i==rr)
            {
                Console.WriteLine("automaton"); return;
            }
            if (chec(s, t) && rr < cc)
            {
                Console.WriteLine("both"); return;
            }
            Console.WriteLine("need tree"); return;

        }
    }
}


using System;
class Program
{
	static void Main()
	{
		string input = Console.ReadLine();
		if (input.Length >= 7 && input.StartsWith('1')) Console.WriteLine("yes");
		else Console.WriteLine("no");
	}
}


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

class Program
{
	static void Main()
	{
		string input = Console.ReadLine();
		if (input.Length >= 7 && input.StartsWith('1')) Console.WriteLine("yes");
		else Console.WriteLine("no");
	}
}


using System;
public class Program
    {
        public static void Main(string[] args)
        {
                    int i = input.IndexOf('1');
                    if (i < 0) Console.WriteLine("no");
                    else
                    {
                        int zeros = 0;
                        for (; i < input.Length; ++i)
                            if (input[i] == '0') zeros++;
                        Console.Write(zeros >= 6 ? "yes" : "no");
                    }
        }
    }


using System; using System.Linq;

class P {
  static void Main() {
    var m = Enumerable.Range(0,3).Select(i =>
              Console.ReadLine().Split(' ').Select(int.Parse).ToArray())
            .ToArray();
    m[0][0] = m[1][1] = m[2][2] = 1;
    var r = new int[3];
    var c = new int[3];
    for (var y=0;y<3;y++)for (var x=0;x<3;x++){r[y]+=m[y][x];c[x]+=m[y][x]; }

    var d1 = m[0][0]+m[1][1]+m[2][2];
    var d2 = m[0][2]+m[1][1]+m[2][0];

    for (var i = 0; ; i = (i+1)%3) {
      var a = new [] { r[0], r[1], r[2],
                       c[0], c[1], c[2],
                       d1, d2 };

      var diff = a.Max() - a.Min();
      if (diff == 0) break;

      var c2 = (new [] { r[i], c[i], i==1?d2:int.MaxValue}).Min();
      diff = a.Max() - c2.Min();
      m[i][i]+=diff; r[i]+=diff; c[i]+=diff; d1 += diff; if (i==2)d2+=diff;
    }
    for (var y = 0; y < 3 ; y++) Console.WriteLine(string.Join(" ", m[y]));
  }
}


using System; using System.Linq;

class P {
  static void Main() {
    var m = Enumerable.Range(0,3).Select(i =>
              Console.ReadLine().Split(' ').Select(int.Parse).ToArray())
            .ToArray();
    m[0][0] = m[1][1] = m[2][2] = 1;
    var r = new int[3];
    var c = new int[3];
    for (var y=0;y<3;y++)for (var x=0;x<3;x++){r[y]+=m[y][x];c[x]+=m[y][x]; }

    var d1 = m[0][0]+m[1][1]+m[2][2];
    var d2 = m[0][2]+m[1][1]+m[2][0];

    for (var i = 0; ; i = (i+1)%3) {
      var a = new [] { r[0], r[1], r[2],
                       c[0], c[1], c[2],
                       d1, d2 };

      var diff = a.Max() - a.Min();
      if (diff == 0) break;

      var c = (new [] { r[i], c[i], i==1?d2:int.MaxValue}).Min();
      diff = a.Max() - c.Min();
      m[i][i]+=diff; r[i]+=diff; c[i]+=diff; d1 += diff; if (i==2)d2+=diff;
    }
    for (var y = 0; y < 3 ; y++) Console.WriteLine(string.Join(" ", m[y]));
  }
}


string[] y = Console.ReadLine().Split();
		int a = int.Parse(y[0]);
		int b = int.Parse(y[1]);
		int c = int.Parse(y[2]);
		char q='?';
		if(a-b-c>0)
		{
			q = '+';
		}
		else if(b-a-c>0)
		{
			q='-';
		}
		else if(a==b && c==0)
		{
			q='0';
		}
		Console.WriteLine(q);


using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine())
            int[] a = new int[n];
            string[] s = Console.ReadLine().Split();
            for (int i = 0; i < n; i++)
            {
                a[i] = int.Parse(s[i]);
            }
            Array.Sort(a);
            Console.WriteLine(a[n / 2 + 1]);
        }
    }
}


 var NumberOfGroup = Convert.ToInt32(Console.ReadLine());
            var Years = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
            if (NumberOfGroup == 1)
            {
                Console.WriteLine(Years[0]);
                return;
            }
            int Answer = Years.Sum() / NumberOfGroup;
            Console.WriteLine(Answer);


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

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {

        int n = Convert.ToInt32(Console.ReadLine());
        var Arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

        if (n == 1)
        {
            Console.WriteLine(Arr[0].ToString());
        }
        else
        {
            Array.Sort(Arr);
            Console.WriteLine(Arr[(n == 3) ? 1 : 2]);
        }

    }
}


using System;

class P {
  static void Main() {
    var n = long.Parse(Console.ReadLine());
    var xmax = Math.Sqrt(n);
    var smax = ((int)Math.Ceiling(Math.Log10(xmax))) *9;

    Func<long, long> sq = a => {
         var sq = (long)Math.Sqrt(a);
         if (sq*sq == a) return sq;
         sq++;
         if (sq*sq == a) return sq;
         return -1;
      };

    for (var s = 1 ; s <= smax ; s++) {
      var d = sq(s*s+4*n);
      if (d < 0) continue;
      var x2 = d - s;
      if (x2 % 2 == 1) continue;
      var x = x2 / 2;
      var tmp = x;
      var sum = 0;
      while (tmp > 0) { sum += tmp % 10; tmp /= 10; }
      if (sum != s) continue;
      Console.Write(x);
      return;
    }
  }
}


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <ProductVersion>8.0.30703</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{8295E71E-212F-4144-A959-F6F329C0C230}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>Nekvadratnoe_yravnenie</RootNamespace>
    <AssemblyName>Nekvadratnoe_yravnenie</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <TargetFrameworkProfile>Client</TargetFrameworkProfile>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <PlatformTarget>x86</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>


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

namespace NonSquareEquation
{
    class Program
    {
        static void Main(string[] args)
        {
            long n=Convert.ToInt64(Console.ReadLine());
            for (long i = 0; i < Int64.MaxValue; i++)
            {
                if(i*i+(s(i)*i)==n)
                {
                    Console.WriteLine(i);
                    return;
                }
            }
            Console.WriteLine("-1");
            return;
        }

        public static int s(long x)
        {
            int temp=0;
            while (x > 0)
            {
                temp = temp + (int)(x % 10);
                x = x / 10;
            }
            return temp;
        }
    }
}


using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string textBox1 = Console.ReadLine();
            string textBox2 = Console.ReadLine();
            int max = textBox1.Length;
            int valor = 0, valorTemp = 0;
            for (int i = 0; i < textBox1.Length; i++)
            {
                if (textBox1[i] == textBox2[0])
                {
                    valorTemp = moduloDeCadenaMasLarga(i + 1,textBox1,textBox2);
                    if (valorTemp > valor)
                    {
                        valor = valorTemp;
                    }
                }
            }

            Console.WriteLine(valor);
        }

        private static int moduloDeCadenaMasLarga(int inicio, string textBox1, string textBox2)
        {
            int longitud = 0;
            int contadorSubcadena = 1;
            int longitudDerecha = 0;
            int inicioIntermedio = inicio;
            int finIntermedio = 0;
            int longitudIntermedio = 0;
            int longitudIntermedioTemp = 0;
            for (int i = inicio; i < textBox1.Text.Length; i++)
            {
                if (textBox1.Text[i] == textBox2.Text[contadorSubcadena])
                {
                    finIntermedio = i - 1;
                    longitudIntermedioTemp = finIntermedio - inicioIntermedio;
                    if (longitudIntermedioTemp > longitudIntermedio)
                    {
                        longitudIntermedio = longitudIntermedioTemp;
                    }
                    inicioIntermedio = i;
                    contadorSubcadena++;
                }
                if (contadorSubcadena == textBox2.Text.Length)
                {
                    longitudDerecha = (textBox1.Text.Length - 1) - i;
                    break;
                }
            }
            if (contadorSubcadena == textBox2.Text.Length)
            {
                if (longitudDerecha > (inicio - 1) && longitudDerecha > longitudIntermedio)
                {
                    longitud = longitudDerecha;
                }
                else if (longitudIntermedio > (inicio - 1))
                {
                    longitud = longitudIntermedio;
                }
                else
                {
                    longitud = inicio - 1;
                }
            }
            return longitud;
        }
    }
}


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

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

            DateTime nextTime = DateTime.Now;
            DateTime currentTime = nextTime.AddYears(1);
            Dictionary<string, int> dict = new Dictionary<string, int>()
            {
                {"Monday", 1 },
                {"Tuesday", 2 },
                {"Wednesday", 3 },
                {"Thursday", 4 },
                {"Friday", 5 },
                {"Saturday", 6 },
                {"Sunday", 7 }
            };

            int[] months = {1,2,3,4,5,6,7,8,9,10,11,12};
            int nextYear = currentTime.Year;

            string[] textAll = Console.ReadLine()?.Split(' ');
            int number = Convert.ToInt32(textAll?[0]);
            string text = textAll?[2];
            int result = 0;

            if (text.Equals("week"))
            {
                foreach (var m in months)
                {
                    int daysInMonth = DateTime.DaysInMonth(nextYear, m);
                    for (int i = 1;i <= daysInMonth; i++ )
                    {
                        DateTime day = new DateTime(currentTime.Year, m, i);
                        DayOfWeek d = day.DayOfWeek;
                        int dInt = dict[d.ToString()];
                        if (number == dInt)
                        {
                            result++;
                        }
                    }
                }
            }
            if (text.Equals("month"))
            {
                foreach (var m in months)
                {
                    int daysInMonth = DateTime.DaysInMonth(nextYear, m);
                    if (number <= daysInMonth)
                    {
                        result++;
                    }
                }
            }
            System.Console.WriteLine(result);
        }
    }
}


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

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

            DateTime nextTime = DateTime.Now;
            DateTime currentTime = nextTime.AddYears(1);
            Dictionary<string, int> dict = new Dictionary<string, int>()
            {
                {"Monday", 1 },
                {"Tuesday", 2 },
                {"Wednesday", 3 },
                {"Thursday", 4 },
                {"Friday", 5 },
                {"Saturday", 6 },
                {"Sunday", 7 }
            };

            int[] months = {1,2,3,4,5,6,7,8,9,10,11,12};
            int nextYear = currentTime.Year;

            string[] textAll = Console.ReadLine().Split(' ');
            int number = Convert.ToInt32(textAll?[0]);
            string text = textAll?[2];
            int result = 0;

            if (text.Equals("week"))
            {
                foreach (var m in months)
                {
                    int daysInMonth = DateTime.DaysInMonth(nextYear, m);
                    for (int i = 1;i <= daysInMonth; i++ )
                    {
                        DateTime day = new DateTime(currentTime.Year, m, i);
                        DayOfWeek d = day.DayOfWeek;
                        int dInt = dict[d.ToString()];
                        if (number == dInt)
                        {
                            result++;
                        }
                    }
                }
            }
            if (text.Equals("month"))
            {
                foreach (var m in months)
                {
                    int daysInMonth = DateTime.DaysInMonth(nextYear, m);
                    if (number <= daysInMonth)
                    {
                        result++;
                    }
                }
            }
            System.Console.WriteLine(result);
        }
    }
}


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

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

            DateTime nextTime = DateTime.Now;
            DateTime currentTime = nextTime.AddYears(1);
            Dictionary<string, int> dict = new Dictionary<string, int>()
            {
                {"Monday", 1 },
                {"Tuesday", 2 },
                {"Wednesday", 3 },
                {"Thursday", 4 },
                {"Friday", 5 },
                {"Saturday", 6 },
                {"Sunday", 7 }
            };

            int[] months = {1,2,3,4,5,6,7,8,9,10,11,12};
            int nextYear = currentTime.Year;

            string[] textAll = Console.ReadLine().Split(' ');
            int number = Convert.ToInt32(textAll[0]);
            string text = textAll?[2];
            int result = 0;

            if (text.Equals("week"))
            {
                foreach (var m in months)
                {
                    int daysInMonth = DateTime.DaysInMonth(nextYear, m);
                    for (int i = 1;i <= daysInMonth; i++ )
                    {
                        DateTime day = new DateTime(currentTime.Year, m, i);
                        DayOfWeek d = day.DayOfWeek;
                        int dInt = dict[d.ToString()];
                        if (number == dInt)
                        {
                            result++;
                        }
                    }
                }
            }
            if (text.Equals("month"))
            {
                foreach (var m in months)
                {
                    int daysInMonth = DateTime.DaysInMonth(nextYear, m);
                    if (number <= daysInMonth)
                    {
                        result++;
                    }
                }
            }
            System.Console.WriteLine(result);
        }
    }
}


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

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

            DateTime currentTime = DateTime.Now;
            currentTime.AddYears(1);
            Dictionary<string, int> dict = new Dictionary<string, int>()
            {
                {"Monday", 1 },
                {"Tuesday", 2 },
                {"Wednesday", 3 },
                {"Thursday", 4 },
                {"Friday", 5 },
                {"Saturday", 6 },
                {"Sunday", 7 }
            };

            int[] months = {1,2,3,4,5,6,7,8,9,10,11,12};
            int nextYear = currentTime.Year;

            string[] textAll = Console.ReadLine()?.Split(' ');
            int number = Convert.ToInt32(textAll?[0]);
            string text = textAll?[2];
            int result = 0;

            if (text.Equals("week"))
            {
                foreach (var m in months)
                {
                    int daysInMonth = DateTime.DaysInMonth(nextYear, m);
                    for (int i = 1;i <= daysInMonth; i++ )
                    {
                        DateTime day = new DateTime(currentTime.Year, m, i);
                        DayOfWeek d = day.DayOfWeek;
                        int dInt = dict[d.ToString()];
                        if (number == dInt)
                        {
                            result++;
                        }
                    }
                }
            }
            if (text.Equals("month"))
            {
                foreach (var m in months)
                {
                    int daysInMonth = DateTime.DaysInMonth(nextYear, m);
                    if (number <= daysInMonth)
                    {
                        result++;
                    }
                }
            }
            System.Console.WriteLine(result);
        }
    }
}


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

public class Program
{

    public void Solve()
    {
        var sc = new Scanner();
        int a = sc.NextInt();
        for (int n = a; ; n++)
        {
            var str = n.ToString();
            var sum = 0;
            foreach (var c in sum)
            {
                sum += c - '0';
            }

            if (sum % 4 == 0)
            {
                Console.WriteLine(n);
                return;
            }
        }
    }

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

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.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Codeforces.Codeforces;

namespace Codeforces
{
    class Program
    {
        public static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());

            for (int i = n; i <= 1000; i++)
            {
                int[] arr = IntArray(i);
                int total = 0;

                for (int k = 0; k < arr.Length; k++)
                {
                    total += arr[k];
                }

                if (total % 4 == 0)
                {
                    Console.WriteLine(i);
                    break;
                }
            }
        }

        public static int[] IntArray(int num)
        {
            List<int> listOfInts = new List<int>();
            while (num > 0)
            {
                listOfInts.Add(num % 10);
                num = num / 10;
            }
            listOfInts.Reverse();
            return listOfInts.ToArray();
        }
    }
}


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30011.22
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeForces", "CodeForces\CodeForces.csproj", "{EED76156-CCE4-42C9-A987-930CFF62AF5F}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{EED76156-CCE4-42C9-A987-930CFF62AF5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{EED76156-CCE4-42C9-A987-930CFF62AF5F}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{EED76156-CCE4-42C9-A987-930CFF62AF5F}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{EED76156-CCE4-42C9-A987-930CFF62AF5F}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {1C1D43E7-DF4C-4656-AEE4-ABD77639473E}
	EndGlobalSection
EndGlobal


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.16
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp1", "ConsoleApp1\ConsoleApp1.csproj", "{ABB1C275-B0DD-4207-98C6-3E1AF08D4A7C}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{ABB1C275-B0DD-4207-98C6-3E1AF08D4A7C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{ABB1C275-B0DD-4207-98C6-3E1AF08D4A7C}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{ABB1C275-B0DD-4207-98C6-3E1AF08D4A7C}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{ABB1C275-B0DD-4207-98C6-3E1AF08D4A7C}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {1753EC7D-E288-4292-84B8-C1654AC04FA8}
	EndGlobalSection
EndGlobal


using System;

namespace _1064A
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            int index = str.IndexOf(' ');
            int a = Convert.ToInt32(str.Substring(0, index));
            str = str.Substring(index + 1);
            index = str.IndexOf(' ');
            int b = Convert.ToInt32(str.Substring(0, index));
            int c = Convert.ToInt32(str.Substring(index));
            int time = 0;
            int[] side = new int[3];
            side[0] = a;
            side[1] = b;
            side[2] = c;

            side = sortArray(side);

            if (a + b > c && a + c > b && b + c > a)
            {
                time = 0;
            }
            else
            {
                while (side[0] + side[1] <= side[2])
                {
                    side[0]++;
                    time++;
                }
            }

            Console.WriteLine(time);

            static int[] sortArray(int[] array)
            {
                int temp;

                for (int i = 0; i < array.Length - 1; i++)
                {
                    for (int j = i + 1; j < array.Length; j++)
                    {
                        if (array[i] > array[j])
                        {
                            temp = array[i];
                            array[i] = array[j];
                            array[j] = temp;
                        }
                    }
                }

                return array;
            }
        }
    }
}


int[] arr = Console.ReadLine().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(str => Convert.ToInt32(str)).ToArray();
int max= arr.Max();//MAX

int SumMins = 0;

int imax = Array.IndexOf(arr, arr.Max());
for (int i = 0; i < arr.Length; i++)
if (i != imax)
SumMins += arr[i];

if (max + 1 < SumMins)
Console.WriteLine(0);
else
Console.WriteLine(max+1-SumMins);


using System;

namespace _1064_Make_a_triangle
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = Array.ConvertAll(Console.ReadLine().Split(" "), int.Parse);
            Array.Sort(a);
            var count = 0;
            while (a[0] + a[1] <= a[2])
            {
                count++;
                a[0]++;
            }

            Console.WriteLine(count);
        }
    }
}


List<string> l = new List<string>();
		public static void Main(string[] args)
		{
			string start = Console.ReadLine();
			string end = Console.ReadLine();
			int start_col = Convert.ToInt32(start[0]);
			int end_col = Convert.ToInt32(end[0]);
			int start_row = Convert.ToInt32(start[1]);
			int end_row = Convert.ToInt32(end[1]);
			char move_vert='0';
			char move_hor='0';
			int hor_dif = Math.Abs(start_col-end_col);
			int vert_dif = Math.Abs(start_row-end_row);
			if(start_col!=end_col){
				if(start_col<end_col){
					move_hor='R';
				} else {
					move_hor='L';
				}
			}
			if(start_row!=end_row){
				if(start_row<end_row){
					move_vert='U';
				} else {
					move_vert='D';
				}
			}
			int dif = 0;
			int min = 0;
			int max = 0;
			if(hor_dif<vert_dif){
				dif = hor_dif+(vert_dif-hor_dif);
				min = hor_dif;
				max = vert_dif;
			} else {
				dif = vert_dif+(hor_dif-vert_dif);
				min = vert_dif;
				max = hor_dif;
			}
			Console.WriteLine(dif);
			for(int i=0; i<min; i++){
				Console.WriteLine(Convert.ToString(move_hor)+move_vert.ToString());
			}
			for(int i=min; i<max; i++){
				if(max==hor_dif){
					Console.WriteLine(move_hor.ToString());
				} else {
					Console.WriteLine(move_vert.ToString());
				}
			}
		}


		public static void Main(string[] args)
		{
			string start = Console.ReadLine();
			string end = Console.ReadLine();
			int start_col = Convert.ToInt32(start[0]);
			int end_col = Convert.ToInt32(end[0]);
			int start_row = Convert.ToInt32(start[1]);
			int end_row = Convert.ToInt32(end[1]);
			char move_vert='0';
			char move_hor='0';
			int hor_dif = Math.Abs(start_col-end_col);
			int vert_dif = Math.Abs(start_row-end_row);
			if(start_col!=end_col){
				if(start_col<end_col){
					move_hor='R';
				} else {
					move_hor='L';
				}
			}
			if(start_row!=end_row){
				if(start_row<end_row){
					move_vert='U';
				} else {
					move_vert='D';
				}
			}
			int dif = 0;
			int min = 0;
			int max = 0;
			if(hor_dif<vert_dif){
				dif = hor_dif+(vert_dif-hor_dif);
				min = hor_dif;
				max = vert_dif;
			} else {
				dif = vert_dif+(hor_dif-vert_dif);
				min = vert_dif;
				max = hor_dif;
			}
			Console.WriteLine(dif);
			for(int i=0; i<min; i++){
				Console.WriteLine(Convert.ToString(move_hor)+move_vert.ToString());
			}
			for(int i=min; i<max; i++){
				if(max==hor_dif){
					Console.WriteLine(move_hor.ToString());
				} else {
					Console.WriteLine(move_vert.ToString());
				}
			}
		}


using System;

public class ProblemA
{
	public static void Main(String[] args)
	{
		int n = Int32.ParseInt(args[0]);

		int solution = 0;

		for (int i=6; i <= n; i++)
		{
			int temp = i;
			int primeDivisorCount = 0;
			if (temp % 2 == 0)
			{
				primeDivisorCount++;
				while (temp % 2 == 0)
				{
					temp = temp / 2;
				}
			}

			int oddDivisor = 3;
			while (temp >= oddDivisor)
			{
				if (temp % oddDivisor == 0)
				{
					primeDivisorCount++;
					if (primeDivisorCount > 2)
					{
						break;
					}
					while (temp % oddDivisor == 0)
					{
						temp = temp / oddDivisor;
					}
				}
				oddDivisor += 2;
			}

			if (primeDivisorCount == 2)
			{
				solution++;
			}
		}
		Console.WriteLine(solution);
	}
}


using System;

namespace CodeForces
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split();
            double d = double.Parse(input[0]);
            double L = double.Parse(input[1]);
            double v1 = double.Parse(input[2]);
            double v2 = double.Parse(input[3]);
            double y = (L - d) / (v1 + v2);
            string answer = y.ToString(CultureInfo.InvariantCulture);
            Console.WriteLine(answer);
        }
    }
}


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2024
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp7", "ConsoleApp7\ConsoleApp7.csproj", "{8D0ED673-8B30-4B7C-8D23-B72BB1BBCF32}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{8D0ED673-8B30-4B7C-8D23-B72BB1BBCF32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{8D0ED673-8B30-4B7C-8D23-B72BB1BBCF32}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{8D0ED673-8B30-4B7C-8D23-B72BB1BBCF32}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{8D0ED673-8B30-4B7C-8D23-B72BB1BBCF32}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {068B1F18-236E-42F9-A338-C473F338CB4E}
	EndGlobalSection
EndGlobal


#include <bits/stdc++.h>
using namespace std;
#define S second
#define F first
#define MOD 1000000007
typedef  long long llint;
typedef pair<int,int> pii;
vector<vector<int> > a;

int main()
{
int N;cin>>N;
int x;
a.assign(N+1,vector<int>(0));
for(int i=1;i<=N;i++)
{
    cin>>x;
    a[x].push_back(i);
    a[i].push_back(x);
}
return 0;
}


//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

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

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //inputs Bitch
            int []ip=Console.ReadLine().Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries).Select(x=>int.Parse(x)).ToArray();
            int d=ip[0],l=ip[1],v1=ip[2],v2=ip[3];
            //logic Bitch
           double ans=l-d;
            ans=ans/Math.Abs(v1+v2);
          Console.WriteLine(ans.ToString(CultureInfo.GetCultureInfo("en-US")));

        }
    }
}


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{8D0ED673-8B30-4B7C-8D23-B72BB1BBCF32}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>ConsoleApp7</RootNamespace>
    <AssemblyName>ConsoleApp7</AssemblyName>
    <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            string[] y = new string[n];
            bool g=false;
            for (int i = 0; i < n; i++)
            {
                string[] temp = Console.ReadLine().Split(' ');
                Int64 a = Int64.Parse(temp[0]);
                Int64 b = Int64.Parse(temp[1]);

                if (Math.Abs(a - b) == 1)
                {
                    bool f = false;
                    for (Int64 j = 2; j < Math.Sqrt(a + b)+2; j++)
                    {
                        if (((a + b) % j == 0)&&(g<=a+b))
                        {
                            f = true;
                            break;
                        }
                    }
                    if (f)
                        Console.WriteLine("NO");
                    else
                        Console.WriteLine("YES");

                }
                else
                    Console.WriteLine("NO");
            }
        }
    }
}


using System;
using System.Linq;

class Program {
  static void Main() {
    var s = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    var n = s[0]; var x = s[1]; var p = s[2];

    var res = (int)Math.Ceil(n*p/100.0)-x;
    Console.Write(res);
  }
}


class Program
    {
        private static double SqrDistance(double x1, double y1, double x2, double y2)
        {
            return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
        }

        static void Main()
        {
            string input = Console.ReadLine();
            string[] intputNumbers = input.Split(' ');

            double x, y;
            x = Convert.ToInt64(intputNumbers[0]);
            y = Convert.ToInt64(intputNumbers[1]);

            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
            double height = Math.Sqrt(SqrDistance(x, y, x, 0));

            if(x > 0 && y > 0)
                Console.Write(0.ToString() + " " + (x + height).ToString() + " " + (x + height).ToString() + " " + 0.ToString());
            else if(x < 0 && y > 0)
                Console.Write((x - height).ToString() + " " + 0.ToString() + " " + 0.ToString() + " " + (-x + height).ToString());
            else if (x < 0 && y < 0)
                Console.Write((x - height).ToString() + " " + 0.ToString() + " " + 0.ToString() + " " + (x - height).ToString());
            else if (x > 0 && y < 0)
                Console.Write(0.ToString() + " " + (x + height).ToString() + " " + (x + height).ToString() + " " + 0.ToString());
        }
    }


private static double SqrDistance(double x1, double y1, double x2, double y2)
        {
            return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
        }

static void Main()
        {
            string input = Console.ReadLine();
            string[] intputNumbers = input.Split(' ');

            double x, y;
            x = Convert.ToInt64(intputNumbers[0]);
            y = Convert.ToInt64(intputNumbers[1]);

            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
            double height = Math.Sqrt(SqrDistance(x, y, x, 0));

            if(x > 0 && y > 0)
                Console.Write(0.ToString() + " " + (x + height).ToString() + " " + (x + height).ToString() + " " + 0.ToString());
            else if(x < 0 && y > 0)
                Console.Write((x - height).ToString() + " " + 0.ToString() + " " + 0.ToString() + " " + (-x + height).ToString());
            else if (x < 0 && y < 0)
                Console.Write((x - height).ToString() + " " + 0.ToString() + " " + 0.ToString() + " " + (x - height).ToString());
            else if (x > 0 && y < 0)
                Console.Write(0.ToString() + " " + (x + height).ToString() + " " + (x + height).ToString() + " " + 0.ToString());
        }


public class Program{
    public static void Main(){
        int x, y;
        string[] line = Console.ReadLine().Split(' ');
        x = int.Parse(line[0]);
        y = int.Parse(line[1]);

        int sum  = Math.Abs(x) + Math.Abs(y);

        if(x > 0 && y > 0)
            Console.WriteLine("{0} {1} {2} {3}", 0, sum, sum, 0);
        else if(x > 0 && y < 0)
            Console.WriteLine("{0} {1} {2} {3}", 0, -sum, sum, 0);
        else if(x < 0 && y > 0)
            Console.WriteLine("{0} {1} {2} {3}", -sum, 0, 0, sum);
        else
            Console.WriteLine("{0} {1} {2} {3}", -sum, 0, 0, -sum);
    }
}


public class Program{
    public static void Main(){
        int x, y;
        string[] line = Console.ReadLine().Split(' ');
        x = int.Parse(line[0]);
        y = int.Parse(line[1]);

        int sum  = Math.Abs(x) + Math.Abs(y);

        if(x > 0 && y > 0)
            Console.WriteLine({0} {1} {2} {3}, 0, sum, sum, 0);
        else if(x > 0 && y < 0)
            Console.WriteLine({0} {1} {2} {3}, 0, -sum, sum, 0);
        else if(x < 0 && y > 0)
            Console.WriteLine({0} {1} {2} {3}, -sum, 0, 0, sum);
        else
            Console.WriteLine({0} {1} {2} {3}, -sum, 0, 0, -sum);
    }
}


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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
#if DEBUG
            Console.SetIn(System.IO.File.OpenText("in.txt"));
#endif
            int[] input = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            int n = input[0];
            int k = input[1];
            string str = Console.ReadLine();

            if (k == 26)
            {
                Console.WriteLine("NO");
                return;
            }
            var lastPositions = new Dictionary<char, int>(26);
            int openGatesCount = 0;
            for (int i = 0; i < n; i++)
            {
                int lastPosition;
                char gate = str[i];
                if (!lastPositions.ContainsKey(gate))
                {
                    openGatesCount++;
                    if (openGatesCount > k)
                    {
                        Console.WriteLine("YES");
                        return;
                    }
                    lastPosition = str.LastIndexOf(gate);
                    lastPositions.Add(gate, lastPosition);
                }
                else
                {
                    lastPosition = lastPositions[gate];
                }
                if (lastPosition == i)
                {
                    openGatesCount--;
                }
            }
            Console.WriteLine("NO");
        }

        static void Gen()
        {
            var stream = new System.IO.StreamWriter("in.txt");
            var rand = new Random();
            for (int i = 0; i < 1_000_000; i++)
            {
                stream.Write((char)('A' + rand.Next(25)));
            }
            stream.Close();
        }
    }
}


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

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var n = Console.ReadLine();
            var str = Console.ReadLine();
            var c = 0;
            var FS = 0;
            var SF = 0;
            for (var i = 2; i < Convert.ToInt32(n); i+=2)
            {

                if (str.Substring(c, i) == "SF")
                    SF++;
                else FS++;
                c = i;
            }
            Console.WriteLine(FS > SF ? "FS" : "SF");
        }
    }
}


using System;
using System.Text.RegularExpressions;

{
    class Program
    {
        static void Main(string[] args)
        {
            var n = Console.ReadLine();
            var str = Console.ReadLine();
            Console.WriteLine(Regex.Matches(str, "SF").Count> Regex.Matches(str, "FS").Count ? "YES" : "NO");
        }
    }


            List<string> arr = new List<string>();
            int n,Y=0,N=0,j2;
            string str,s1,s2;
            n = int.Parse(Console.ReadLine());
            for (int i = 0; i < n; i++)
            {
                arr.Add(Console.ReadLine());
            }
            for (int j = 0; j < n; j++)
            {
                if (j+1 < n)
                {
                    str = string.Concat(arr[j], arr[j + 1]);
                    if (str == "SF")
                    {
                        Y += 1;
                    }
                    if (str == "FS")
                    {
                        N += 1;
                    }
                }

            }//for
            if (Y>N)
            {
                Console.WriteLine("YES");
            }
            else
            {
                Console.WriteLine("NO");
            }


    class Program
    {
        static void Main(string[] args)
        {
            var n = Console.ReadLine();
            var str = Console.ReadLine();
            var c = 0;
            var FS = 0;
            var SF = 0;
            for (var i = 2; i < Convert.ToInt32(n); i+=2)
            {

                if (str.Substring(c, i) == "SF")
                    SF++;
                else FS++;
                c = i;
            }
            Console.WriteLine(FS > SF ? "FS" : "SF");
        }
    }


using System;

public class Program
{
    public static void Main()
    {
        int A = int.Parse(Console.ReadLine());
        string joy = Console.ReadLine();
        int b=joy.Length;
        if(joy[0]=='S'&&joy[b-1]=='F')
        {
            Console.WriteLine("YES");

        }
        else
        {
            Console.WriteLine("NO");
        }

    }
}


 static void Main(string[] args)
        {
            var n = Console.ReadLine();
            var str = Console.ReadLine();
            var c = 0;
            var FS = 0;
            var SF = 0;
            for (var i = 2; i < Convert.ToInt32(n); i+=2)
            {

                if (str.Substring(c, i) == "SF")
                    SF++;
                else FS++;
                c = i;
            }
            Console.WriteLine(FS > SF ? "FS" : "SF");
        }


using System;
using System.Text.RegularExpressions;
static void Main(string[] args)
{
            var n = Console.ReadLine();
            var str = Console.ReadLine();
            Console.WriteLine(Regex.Matches(str, "SF").Count> Regex.Matches(str, "FS").Count ? "YES" : "NO");
}


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.16
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp10", "ConsoleApp10\ConsoleApp10.csproj", "{892D3637-102B-45A3-BCEA-60A9F01CE1C1}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{892D3637-102B-45A3-BCEA-60A9F01CE1C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{892D3637-102B-45A3-BCEA-60A9F01CE1C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{892D3637-102B-45A3-BCEA-60A9F01CE1C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{892D3637-102B-45A3-BCEA-60A9F01CE1C1}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {E31B0511-87CC-4B41-8654-8DF6F2D9E161}
	EndGlobalSection
EndGlobal


class Program
{
    static void Main(){
        var n = int.Parse(Console.ReadLine());
            var str = "";
            for(int i = 1; i<5000; i++)
            {
                str += i.ToString();
            }
            Console.WriteLine(str[n]);
    }
}


using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using static System.Math;

// https://codeforces.com/contest/1154/problem/C
public class GourmetCat
{
    private static void Solve()
    {
        int[] a = ReadIntArray();
        int[] week = new int[14] { 0, 1, 2, 0, 2, 1, 0, 0, 1, 2, 0, 2, 1, 0, };

        // Get maximum common weeks
        int nWeeks = Min(a[0] / 3, Min(a[1] / 2, a[2] / 2));
        eat[0] -= n * 3;
        eat[1] -= n * 2;
        eat[2] -= n * 2;

        // Add extra days that conform less than a week
        int max = 0;
        for (int i = 0; i < 7; i++)
        {
            int[] aClone = (int[])a.Clone();
            int j;
            for (j = i; j < i + 7; j++)
            {
                if (aClone[week[j]] == 0)
                    break;
                aClone[week[j]]--;
            }

            if (j - i > max)
                max = j - i;
        }

        Write(nWeeks * 7 + max);
    }

    #region Main

    private static TextReader reader;
    private static TextWriter writer;

    public static void Main()
    {
#if DEBUG

        //reader = new StreamReader("C:\\Users\\Axel\\Desktop\\input.txt");
        reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;

        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());

        //reader = new StreamReader("input.txt");
        //writer = new StreamWriter("output.txt");
#endif
        try
        {
            Solve();

            //var thread = new Thread(new String_Task().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
#if DEBUG
#else
            throw;
#endif
        }
        reader.Close();
        writer.Close();
    }

    #endregion Main

    #region Read / Write

    private static Queue<string> currentLineTokens = new Queue<string>();

    private static string[] ReadAndSplitLine()
    {
        return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries);
    }

    public static string Read()
    {
        while (currentLineTokens.Count == 0) currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue();
    }

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

    public static long ReadLong()
    {
        return long.Parse(Read());
    }

    public static double ReadDouble()
    {
        return double.Parse(Read(), CultureInfo.InvariantCulture);
    }

    public static int[] ReadIntArray()
    {
        return ReadAndSplitLine().Select(int.Parse).ToArray();
    }

    public static long[] ReadLongArray()
    {
        return ReadAndSplitLine().Select(long.Parse).ToArray();
    }

    public static double[] ReadDoubleArray()
    {
        return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray();
    }

    public static int[][] ReadIntMatrix(int numberOfRows)
    {
        int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++) matrix[i] = ReadIntArray(); return matrix;
    }

    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++) ret[i][j] = matrix[j][i]; }
        return ret;
    }

    public static string[] ReadLines(int quantity)
    {
        string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++) lines[i] = reader.ReadLine().Trim(); return lines;
    }

    public static void WriteArray<T>(IEnumerable<T> array)
    {
        writer.WriteLine(string.Join(" ", array));
    }

    public static void Write(params object[] array)
    {
        WriteArray(array);
    }

    public static void WriteLines<T>(IEnumerable<T> array)
    {
        foreach (var a in array) writer.WriteLine(a);
    }

    private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        public new TValue this[TKey key]
        {
            get { return ContainsKey(key) ? base[key] : default(TValue); }
            set { base[key] = value; }
        }
    }

    private static T[] Init<T>(int size) where T : new()
    {
        var ret = new T[size]; for (int i = 0; i < size; i++) ret[i] = new T(); return ret;
    }

    #endregion Read / Write
}


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

namespace ConsoleApplication1
{
    class examples
    {
        static void Main(string[] args)
        {
            int r, m, a, b, f, g;
            string[] rick = Console.ReadLine().Split();
            string[] morty = Console.ReadLine().Split();
            r = int.Parse(rick[0]);
            a = int.Parse(rick[1]);
            m = int.Parse(morty[0]);
            b = int.Parse(morty[1]);
            for (int i = 0; i < 1000; i++)
            {
                f = a + i * r;
                for (int j = 0; j < 1000; j++)
                {
                    g = b + j * m;
                    if (g == f)
                    {
                        Console.Write(f);
                        goto A;
                    }
                }
            }

            Console.Write(-1);
        A:
        }
    }
}


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

namespace mochila
{
    class Rick
    {
        public int Grito { get; set; }

        public Rick(int grito)
        {
            Grito = grito;
        }
    }

    class Program
    {
        static bool verificaGritos(int a, int b, int c, int d)
        {
            int SomaRick = a + b;
            int SomaMorty = c + d;
            int diferenca = 0;

            if (SomaRick > SomaMorty)
            {
                diferenca = SomaRick - SomaMorty;

                if (diferenca > c)
                    return false;
                else
                    return true;
            }
            else
            {
                diferenca = SomaMorty - SomaRick;

                if (diferenca > a)
                    return false;
                else
                    return true;
            }
        }

        static int comparaComRick(List<Rick> lista, int morty)
        {
            int igual = -1;

            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].Grito == morty)
                {
                    igual = morty;
                }
            }

            return igual;
        }

        static void verificaGritosIguais(int a, int b, int c, int d)
        {
            List<Rick> lista = new List<Rick>();
            int cont = 1, rick = 0, morty = 0, igual = -1;   // Igual j� come�a com -1, caso n�o entre no if, j� sai -1 igual o problema pede

            if (verificaGritos(a, b, c, d))
            {
                do
                {
                    rick = b + (a * cont);        // sequ�ncia de gritos de Rick.
                    morty = c + (d * cont);       // sequ�ncia de gritos de Morty.

                    cont++;                       // contador da sequ�ncia.

                    lista.Add(new Rick(rick));    // Somente o grito do Rick � guardado

                    igual = comparaComRick(lista, morty);   // Vai comparar o grito do morty com os gritos guardados do Rick

                } while (igual != morty);         // Enquanto n�o gritarem ao mesmo tempo

                Console.WriteLine(igual);
            }
            else
            {
                Console.WriteLine(igual);
            }
        }

        static void Main(string[] args)
        {
            string R = Console.ReadLine();
            int a = (int)((R.Split(" "))[0]);
            int b = (int)((R.Split(" "))[1]);

            string M = Console.ReadLine();
            int c = (int)((R.Split(" "))[0]);
            int d = (int)((R.Split(" "))[1]);

            verificaGritosIguais(a, b, c, d);
        }
    }
}


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

namespace mochila
{
    class Rick
    {
        public int Grito { get; set; }

        public Rick(int grito)
        {
            Grito = grito;
        }
    }

    class Program
    {
        static bool verificaGritos(int a, int b, int c, int d)
        {
            int SomaRick = a + b;
            int SomaMorty = c + d;
            int diferenca = 0;

            if (SomaRick > SomaMorty)
            {
                diferenca = SomaRick - SomaMorty;

                if (diferenca > c)
                    return false;
                else
                    return true;
            }
            else
            {
                diferenca = SomaMorty - SomaRick;

                if (diferenca > a)
                    return false;
                else
                    return true;
            }
        }

        static int comparaComRick(List<Rick> lista, int morty)
        {
            int igual = -1;

            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].Grito == morty)
                {
                    igual = morty;
                }
            }

            return igual;
        }

        static void verificaGritosIguais(int a, int b, int c, int d)
        {
            List<Rick> lista = new List<Rick>();
            int cont = 1, rick = 0, morty = 0, igual = -1;   // Igual j� come�a com -1, caso n�o entre no if, j� sai -1 igual o problema pede

            if (verificaGritos(a, b, c, d))
            {
                do
                {
                    rick = b + (a * cont);        // sequ�ncia de gritos de Rick.
                    morty = c + (d * cont);       // sequ�ncia de gritos de Morty.

                    cont++;                       // contador da sequ�ncia.

                    lista.Add(new Rick(rick));    // Somente o grito do Rick � guardado

                    igual = comparaComRick(lista, morty);   // Vai comparar o grito do morty com os gritos guardados do Rick

                } while (igual != morty);         // Enquanto n�o gritarem ao mesmo tempo

                Console.WriteLine(igual);
            }
            else
            {
                Console.WriteLine(igual);
            }
        }

        static void Main(string[] args)
        {
            string R = Console.ReadLine();
            int a = (int)char.Parse((R.Split(" "))[0]);
            int b = (int)char.Parse((R.Split(" "))[1]);

            string M = Console.ReadLine();
            int c = (int)char.Parse((R.Split(" "))[0]);
            int d = (int)char.Parse((R.Split(" "))[1]);

            verificaGritosIguais(a, b, c, d);
        }
    }
}


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

namespace c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int e, z=0;

            string[] qwe = Console.ReadLine().Split(' ');
            string[] qwe3 = Console.ReadLine().Split(' ');
            asd1 = int.Parse(qwe[0]);
            asd2 = int.Parse(qwe[1]);
            qwe1= int.Parse(qwe3[0]);
            qwe2 = int.Parse(qwe3[1]);

            for (int f = 1; f < 1000000; f++)
            {
                e = asd1 + asd2 * f;
                for (int ss = 1; ss < 1000000; ss++)
                {
                    z = qwe1 + qwe2 * ss;
                    if (e == z)
                    {
                        Console.Write(e);
                    }
                    else
                    {
                        Console.Write("-1");
                    }
                }

            }

            Console.ReadKey();
        }
    }
}


using System;

namespace C_
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] strArr;
            string str=Console.ReadLine();
            strArr=str.Split(" ");
            int a=Convert.ToInt32(strArr[0]);
            int b=Convert.ToInt32(strArr[1]);
            str=Console.ReadLine();
            strArr=str.Split(" ");
            int c=Convert.ToInt32(strArr[0]);
            int d=Convert.ToInt32(strArr[1]);
            for(int i=0;i<100;i++){
                for(int j=0;j<100;j++){
                    if((a*i)+b==(c*j)+d){
                    Console.WriteLine((a*i)+b);
                    return ;
                    }
                }
            }
            Console.WriteLine(-1);
        }
    }
}


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

namespace mochila
{
    class Rick
    {
        public int Grito { get; set; }

        public Rick(int grito)
        {
            Grito = grito;
        }
    }

    class Program
    {
        static bool verificaGritos(int a, int b, int c, int d)
        {
            int SomaRick = a + b;
            int SomaMorty = c + d;
            int diferenca = 0;

            if (SomaRick > SomaMorty)
            {
                diferenca = SomaRick - SomaMorty;

                if (diferenca > c)
                    return false;
                else
                    return true;
            }
            else
            {
                diferenca = SomaMorty - SomaRick;

                if (diferenca > a)
                    return false;
                else
                    return true;
            }
        }

        static int comparaComRick(List<Rick> lista, int morty)
        {
            int igual = -1;

            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].Grito == morty)
                {
                    igual = morty;
                }
            }

            return igual;
        }

        static void verificaGritosIguais(int a, int b, int c, int d)
        {
            List<Rick> lista = new List<Rick>();
            int cont = 1, rick = 0, morty = 0, igual = -1;   // Igual j� come�a com -1, caso n�o entre no if, j� sai -1 igual o problema pede

            if (verificaGritos(a, b, c, d))
            {
                do
                {
                    rick = b + (a * cont);        // sequ�ncia de gritos de Rick.
                    morty = c + (d * cont);       // sequ�ncia de gritos de Morty.

                    cont++;                       // contador da sequ�ncia.

                    lista.Add(new Rick(rick));    // Somente o grito do Rick � guardado

                    igual = comparaComRick(lista, morty);   // Vai comparar o grito do morty com os gritos guardados do Rick

                } while (igual != morty);         // Enquanto n�o gritarem ao mesmo tempo

                Console.WriteLine(igual);
            }
            else
            {
                Console.WriteLine(igual);
            }
        }

        static void Main(string[] args)
        {
            string R = Console.ReadLine();
            int a = (int)((R.split(" "))[0]);
            int b = (int)((R.split(" "))[1]);

            string M = Console.ReadLine();
            int c = (int)((R.split(" "))[0]);
            int d = (int)((R.split(" "))[1]);

            verificaGritosIguais(a, b, c, d);
        }
    }
}


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

namespace mochila
{
    class Rick
    {
        public int Grito { get; set; }

        public Rick(int grito)
        {
            Grito = grito;
        }
    }

    class Program
    {
        static bool verificaGritos(int a, int b, int c, int d)
        {
            int SomaRick = a + b;
            int SomaMorty = c + d;
            int diferenca = 0;

            if (SomaRick > SomaMorty)
            {
                diferenca = SomaRick - SomaMorty;

                if (diferenca > c)
                    return false;
                else
                    return true;
            }
            else
            {
                diferenca = SomaMorty - SomaRick;

                if (diferenca > a)
                    return false;
                else
                    return true;
            }
        }

        static int comparaComRick(List<Rick> lista, int morty)
        {
            int igual = -1;

            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].Grito == morty)
                {
                    igual = morty;
                }
            }

            return igual;
        }

        static void verificaGritosIguais(int a, int b, int c, int d)
        {
            List<Rick> lista = new List<Rick>();
            int cont = 1, rick = 0, morty = 0, igual = -1;   // Igual j� come�a com -1, caso n�o entre no if, j� sai -1 igual o problema pede

            if (verificaGritos(a, b, c, d))
            {
                do
                {
                    rick = b + (a * cont);        // sequ�ncia de gritos de Rick.
                    morty = c + (d * cont);       // sequ�ncia de gritos de Morty.

                    cont++;                       // contador da sequ�ncia.

                    lista.Add(new Rick(rick));    // Somente o grito do Rick � guardado

                    igual = comparaComRick(lista, morty);   // Vai comparar o grito do morty com os gritos guardados do Rick

                } while (igual != morty);         // Enquanto n�o gritarem ao mesmo tempo

                Console.WriteLine(igual);
            }
            else
            {
                Console.WriteLine(igual);
            }
        }

        static void Main(string[] args)
        {
            string R = Console.ReadLine();
            int a = int.Parse(R.split()[0]);
            int b = int.Parse(R.split()[1]);

            string M = Console.ReadLine();
            int c = int.Parse(M.split()[0]);
            int d = int.Parse(M.split()[1]);

            verificaGritosIguais(a, b, c, d);
        }
    }
}


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

namespace c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int e, z=0;

            string[] qwe = Console.ReadLine().Split(' ');
            string[] qwe2 = Console.ReadLine().Split(' ');
            asd1 = int.Parse(qwe[0]);
            asd2 = int.Parse(qwe[1]);
            qwe1= int.Parse(qwe2[0]);
            qwe2 = int.Parse(qwe2[1]);

            for (int f = 1; f < 1000000; f++)
            {
                e = asd1 + asd2 * f;
                for (int ss = 1; ss < 1000000; ss++)
                {
                    z = qwe1 + qwe2 * ss;
                    if (e == z)
                    {
                        Console.Write(e);
                    }
                    else
                    {
                        Console.Write("-1");
                    }
                }

            }

            Console.ReadKey();
        }
    }
}


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

namespace c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int e, z=0;

            string[] qwe = Console.ReadLine().Split(' ');
            string[] qwe2 = Console.ReadLine().Split(' ');
            int asd1 = int.Parse(qwe[0]);
            int asd2 = int.Parse(qwe[1]);
            int qwe1= int.Parse(qwe2[0]);
            int qwe2 = int.Parse(qwe2[1]);

            for (int f = 1; f < 1000000; f++)
            {
                e = asd1 + asd2 * f;
                for (int ss = 1; ss < 1000000; ss++)
                {
                    z = qwe1 + qwe2 * ss;
                    if (e == z)
                    {
                        Console.Write(e);
                    }
                    else
                    {
                        Console.Write("-1");
                    }
                }

            }

            Console.ReadKey();
        }
    }
}


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

namespace c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int e, z=0;

            string[] qwe = Console.ReadLine().Split(' ');
            string[] qwe2 = Console.ReadLine().Split(' ');
            asd1 = int.Parse(qwe[0]);
            asd2 = int.Parse(qwe[1]);
            qwe1= int.Parse(qwe2[0]);
            qwe2 = int.Parse(qwe2[1]);

            for (int f = 1; f < 1000000; f++)
            {
                e = asd1 + asd2 * f;
                for (int ss = 1; ss < 1000000; ss++)
                {
                    z = qwe1 + qwe2 * ss;
                    if (e == z)
                    {
                        Console.Write(e);
                    }
                    else
                    {
                        Console.Write("-1");
                    }
                }

            }

        }
    }
}


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

namespace mochila
{
    class Rick
    {
        public int Grito { get; set; }

        public Rick(int grito)
        {
            Grito = grito;
        }
    }

    class Program
    {
        static bool verificaGritos(int a, int b, int c, int d)
        {
            int SomaRick = a + b;
            int SomaMorty = c + d;
            int diferenca = 0;

            if (SomaRick > SomaMorty)
            {
                diferenca = SomaRick - SomaMorty;

                if (diferenca > c)
                    return false;
                else
                    return true;
            }
            else
            {
                diferenca = SomaMorty - SomaRick;

                if (diferenca > a)
                    return false;
                else
                    return true;
            }
        }

        static int comparaComRick(List<Rick> lista, int morty)
        {
            int igual = -1;

            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i].Grito == morty)
                {
                    igual = morty;
                }
            }

            return igual;
        }

        static void verificaGritosIguais(int a, int b, int c, int d)
        {
            List<Rick> lista = new List<Rick>();
            int cont = 1, rick = 0, morty = 0, igual = -1;   // Igual j� come�a com -1, caso n�o entre no if, j� sai -1 igual o problema pede

            if (verificaGritos(a, b, c, d))
            {
                do
                {
                    rick = b + (a * cont);        // sequ�ncia de gritos de Rick.
                    morty = c + (d * cont);       // sequ�ncia de gritos de Morty.

                    cont++;                       // contador da sequ�ncia.

                    lista.Add(new Rick(rick));    // Somente o grito do Rick � guardado

                    igual = comparaComRick(lista, morty);   // Vai comparar o grito do morty com os gritos guardados do Rick

                } while (igual != morty);         // Enquanto n�o gritarem ao mesmo tempo

                Console.WriteLine(igual);
            }
            else
            {
                Console.WriteLine(igual);
            }
        }

        static void Main(string[] args)
        {
            string R = Console.ReadLine();
            int a = int.Parse(R.Split("")[0]);
            int b = int.Parse(R.Split("")[1]);

            string M = Console.ReadLine();
            int c = int.Parse(M.Split("")[0]);
            int d = int.Parse(M.Split("")[1]);

            verificaGritosIguais(a, b, c, d);
        }
    }
}


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

namespace c_sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int e, z=0;

            string[] qwe = Console.ReadLine().Split(' ');
            string[] qwe2 = Console.ReadLine().Split(' ');
            asd1 = int.Parse(qwe[0]);
            asd2 = int.Parse(qew[1]);
            qwe1= int.Parse(qew2[0]);
            qwe2 = int.Parse(qew2[1]);

            for (int f = 1; f < 1000000; f++)
            {
                e = asd1 + asd2 * f;
                for (int ss = 1; ss < 1000000; ss++)
                {
                    z = qwe1 + qwe2 * ss;
                    if (e == z)
                    {
                        Console.Write(e);
                    }
                    else
                    {
                        Console.Write("-1");
                    }
                }

            }

            Console.ReadKey();
        }
    }
}


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

namespace ConsoleApplication1
{
    class examples
    {
        static void Main(string[] args)
        {
            int r,m,a,b,f,g;
            string[] rick = Console.ReadLine().Split();
            string[] morty = Console.ReadLine().Split();
            r = int.Parse(rick[0]);
            a = int.Parse(rick[1]);
            m = int.Parse(morty[0]);
            b = int.Parse(morty[1]);
            for (int i = 0; i < 1000; i++)
            {
                f = a + i * r;
                for (int j = 0; j <1000; j++)
                {
                    g = b + j * m;
                    if (g == f)
                    {
                        Console.Write(f);
                        goto A;
                    }
                }
            }

                Console.Write(-1);
            A:
        }
    }
}