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

class Program
{

    void solve()
    {

        int n = nextInt();
        int m = nextInt();
        int k = nextInt();
        int[] x = new int[k];
        int[] y = new int[k];
        for (int i = 0; i < k; i++)
        {
            x[i] = nextInt();
            y[i] = nextInt();
        }
        string res = "NO";
        for (int i = 0; i < k; i++)
            if (can(x[i], y[i], n, m))
                res = "YES";
        println(res);
    }

    private bool can(int x, int y, int n, int m)
    {
        if (x <= 8 || y <= 8 || n - x + 1 <= 8 || m - y + 1 <= 8)
            return true;
        else
            return false;
    }

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

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

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

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

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

Volodya and Vlad play the following game. There are k pies at the cells of n  ×  m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.

First line contains 3 integers, separated by space: 1 ≤ n, m ≤ 100 — dimensions of the board and 0 ≤ k ≤ 100 — the number of pies. Each of the next k lines contains 2 integers, separated by space: 1 ≤ x ≤ n, 1 ≤ y ≤ m — coordinates of the corresponding pie. There could be more than one pie at a cell.

Output only one word: "YES" — if Volodya wins, "NO" — otherwise.

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

namespace ProgrammingContest.Codeforces.Round51
{
    class C
    {
        public static void Main()
        {
            Scanner scanner = Scanner.FromConsole();
            int n = scanner.NextInt(), m = scanner.NextInt();
            int k = scanner.NextInt();
            int nearest = int.MaxValue;
            for (int i = 0; i < k; i++)
            {
                int x = scanner.NextInt(),
                    y = scanner.NextInt();
                int minx = Math.Min(x, n - x + 1),
                    miny = Math.Min(y, m - y + 1);
                nearest = Math.Min(nearest, Math.Min(minx, miny));
            }
            Console.WriteLine(nearest < 6 ? "YES" : "NO");
        }

        #region Scanner
        public class Scanner : IDisposable
        {
            const int MAX_BUFFER_SIZE = 1024 * 1024 * 16;
            const string DELIMITER = " \r\n\t";

            System.IO.TextReader stream;
            int pos = 0, len = 0;
            bool endStream = false;
            int BufferSize = MAX_BUFFER_SIZE;
            char[] buffer = new char[MAX_BUFFER_SIZE];

            public enum Option { Buffering, NoBuffering }

            public Scanner(System.IO.TextReader stream, Option bufferingOption)
            {
                this.stream = stream;
                if (bufferingOption == Option.NoBuffering) BufferSize = 1;
            }

            void ReadBuffer()
            {
                pos = 0;
                len = stream.ReadBlock(buffer, 0, BufferSize);
                endStream = len == 0;
            }

            void SkipDelimiter()
            {
                while (!endStream && IsDelimiter(Peek())) NextChar();
            }

            static bool IsDelimiter(char c)
            {
                return DELIMITER.Contains(c);
            }

            bool Continue(char c)
            {
                return !endStream && !IsDelimiter(c);
            }

            char Peek()
            {
                if (pos >= len) ReadBuffer();
                return buffer[pos];
            }

            public char NextChar()
            {
                if (pos >= len) ReadBuffer();
                return buffer[pos++];
            }

            public string NextString()
            {
                SkipDelimiter();
                StringBuilder res = new StringBuilder();
                for (char c = NextChar(); Continue(c); c = NextChar()) res.Append(c);
                return res.ToString();
            }

            public int NextInt()
            {
                SkipDelimiter();
                int res = 0;
                char c = NextChar();
                int sign = 1;
                if (c == '-') { sign = -1; c = NextChar(); }
                for (; Continue(c); c = NextChar())
                    res = res * 10 + (c - '0');
                return sign * res;
            }

            public long NextLong()
            {
                SkipDelimiter();
                long res = 0;
                char c = NextChar();
                long sign = 1;
                if (c == '-') { sign = -1; c = NextChar(); }
                for (; Continue(c); c = NextChar())
                    res = res * 10 + (c - '0');
                return sign * res;
            }

            public double NextDouble()
            {
                return double.Parse(NextString());
            }

            public int[] NextInts(int n)
            {
                int[] res = new int[n];
                for (int i = 0; i < n; i++) res[i] = NextInt();
                return res;
            }

            public long[] NextLongs(int n)
            {
                long[] res = new long[n];
                for (int i = 0; i < n; i++) res[i] = NextLong();
                return res;
            }

            public double[] NextDoubles(int n)
            {
                double[] res = new double[n];
                for (int i = 0; i < n; i++) res[i] = NextDouble();
                return res;
            }

            public string[] NextStrings(int n)
            {
                string[] res = new string[n];
                for (int i = 0; i < n; i++) res[i] = NextString();
                return res;
            }

            public static Scanner FromString(string s)
            {
                return new Scanner(new System.IO.StreamReader(new System.IO.MemoryStream(Encoding.ASCII.GetBytes(s))), Option.Buffering);
            }

            public static Scanner FromFile(string path)
            {
                return new Scanner(new System.IO.StreamReader(path), Option.Buffering);
            }

            public static Scanner FromConsole()
            {
                return new Scanner(Console.In, Option.Buffering);
            }

            public void Dispose()
            {
                stream.Close();
            }
        }
        #endregion
    }
}


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

namespace ConsoleApplication2
{
    class Program
    {
        private static int ReadInt()
        {
            return int.Parse(Console.ReadLine());
        }

        private static int[] ReadIntArray()
        {
            string[] tmp = Console.ReadLine().Split(' ');
            int[] ans = new int[tmp.Length];
            for (int i = 0; i < tmp.Length; i++) ans[i] = int.Parse(tmp[i]);
            return ans;
        }

        private static long[] ReadLongArray()
        {
            string[] tmp = Console.ReadLine().Split(' ');
            long[] ans = new long[tmp.Length];
            for (int i = 0; i < tmp.Length; i++) ans[i] = long.Parse(tmp[i]);
            return ans;
        }

        private static string[] ReadStringArray()
        {
            string[] tmp = Console.ReadLine().Split(' ');
            return tmp;
        }

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

        private static long Simulate(long h1, long a1, long x1, long y1, List<long> visits1,
            long h2, long a2, long x2, long y2, List<long> visits2)
        {
            long iterations = m + m + m;
            for (long i = 0; i <= iterations; i++)
            {
                if (h1 == a1) visits1.Add(i);
                if (h2 == a2) visits2.Add(i);
                if (h1 == a1 && h2 == a2) return i;
                h1 = (h1 * x1 + y1) % m;
                h2 = (h2 * x2 + y2) % m;
            }

            return - 1;
        }

        private static int Count;
        private static long m;
        private static List<long> Visits1= new List<long>();
        private static List<long> Visits2 =new List<long>();
        static void Main(string[] args)
        {/*
            m = 1007;
            Visits = new List<long>();
            GetList(111, 77, 15, 23);*/

            m = ReadInt();
            int[] tmp = ReadIntArray();
            long h1 = tmp[0];long a1 = tmp[1];
            tmp = ReadIntArray();
            long x1 = tmp[0]; long y1 = tmp[1];
            tmp = ReadIntArray();
            long h2 = tmp[0]; long a2 = tmp[1];
            tmp = ReadIntArray();
            long x2 = tmp[0]; long y2 = tmp[1];

            long ans = Simulate(h1, a1, x1, y1, Visits1,
                h2, a2, x2, y2, Visits2);

            if (ans > -1)
            {
                Console.Write(ans);
                return;
            }

            if (Visits1.Count == 0 || Visits2.Count == 0)
            {
                Console.Write(-1);
                return;
            }

            if (Visits1.Count == 1)
            {
                if (Visits2.Contains(Visits1[0]))
                {
                    Console.WriteLine(Visits1[0]);
                }
                else
                {
                    Console.WriteLine(-1);
                }
                return;
            }

            if (Visits2.Count == 1)
            {
                if (Visits1.Contains(Visits2[0]))
                {
                    Console.WriteLine(Visits2[0]);
                }
                else
                {
                    Console.WriteLine(-1);
                }
                return;
            }

            long c1 = Visits1[Visits1.Count - 1] - Visits1[Visits1.Count - 2];
            long c2 = Visits2[Visits2.Count - 1] - Visits2[Visits2.Count - 2];
            long d1 = Visits1[Visits1.Count - 1];
            long d2 = Visits2[Visits2.Count - 1];

            if (c1 < c2)
            {
                long qwe = c1;
                c1 = c2;
                c2 = qwe;

                qwe = d1;
                d1 = d2;
                d2 = qwe;
            }

            //long iteration = Math.Max
            for (long i = 0; i <= 5000000; i++)
            {
                long sum = d1 + c1 * i;

                if (sum % c2 == d2)
                {
                    Console.Write(sum);
                    return;
                }
            }

            Console.Write(-1);
        }

        private const int BufferSize = 1 << 16;
        private static readonly StreamReader consoleReader = new StreamReader(Console.OpenStandardInput(BufferSize), Encoding.ASCII, false, BufferSize);
        private static readonly StreamWriter consoleWriter = new StreamWriter(Console.OpenStandardOutput(BufferSize), Encoding.ASCII, BufferSize);

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

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

Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar.  So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become  and height of Abol will become  where x1, y1, x2 and y2 are some integer numbers and  denotes the remainder of a modulo b.Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.Mike has asked you for your help. Calculate the minimum time or say it will never happen.

The first line of input contains integer m (2 ≤ m ≤ 106). The second line of input contains integers h1 and a1 (0 ≤ h1, a1 < m). The third line of input contains integers x1 and y1 (0 ≤ x1, y1 < m). The fourth line of input contains integers h2 and a2 (0 ≤ h2, a2 < m). The fifth line of input contains integers x2 and y2 (0 ≤ x2, y2 < m). It is guaranteed that h1 ≠ a1 and h2 ≠ a2.

Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.

NoteIn the first sample, heights sequences are following:Xaniar: Abol:

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

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

        private static void Main(string[] args)
        {
            int m = Next();
            int h1 = Next(), a1 = Next();
            int x1 = Next(), y1 = Next();
            int h2 = Next(), a2 = Next();
            int x2 = Next(), y2 = Next();

            long index1_1 = -1;
            int index1_2 = -1;

            for (int i = 1; i < 2*m; i++)
            {
                h1 = (int) (((long) x1*h1 + y1)%m);
                if (h1 == a1)
                {
                    if (index1_1 == -1)
                    {
                        index1_1 = i;
                    }
                    else
                    {
                        if (index1_2 == -1)
                        {
                            index1_2 = (int) (i - index1_1);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            long index2_1 = -1;
            int index2_2 = -1;

            for (int i = 1; i < 2*m; i++)
            {
                h2 = (int) (((long) x2*h2 + y2)%m);
                if (h2 == a2)
                {
                    if (index2_1 == -1)
                    {
                        index2_1 = i;
                    }
                    else
                    {
                        if (index2_2 == -1)
                        {
                            index2_2 = (int) (i - index2_1);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            if (index1_1 == index2_1)
            {
                writer.WriteLine(index1_1);
                writer.Flush();
                return;
            }

            if (index1_2 == -1 && index2_2 == -1)
            {
                writer.WriteLine(-1);
                writer.Flush();
                return;
            }

            for (int i = 0; i < m; i++)
            {
                while (index1_2 > 0 && index1_1 < index2_1)
                {
                    index1_1 += index1_2;
                }

                if (index1_1 == index2_1)
                {
                    writer.WriteLine(index1_1);
                    writer.Flush();
                    return;
                }

                while (index2_2 > 0 && index2_1 < index1_1)
                {
                    index2_1 += index2_2;
                }

                if (index1_1 == index2_1)
                {
                    writer.WriteLine(index1_1);
                    writer.Flush();
                    return;
                }
            }

            writer.WriteLine("-1");
            writer.Flush();
        }

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


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

namespace _37E
{
	class Vertex
	{
		public int V;
		public char Color;
		public HashSet<Vertex> Adjast = new HashSet<Vertex>();

		public override string ToString()
		{
			return V.ToString() + "(" + Color + ")";
		}
	}

	class Solver
	{
		public int N { get; set; }
		public int M { get; set; }
		public string[] Board { get; set; }
		int[,] Mask;
		Dictionary<int, Vertex> Graph = new Dictionary<int, Vertex>();

		public Solver(int N, int M, string[] board)
		{
			this.N = N;
			this.M = M;
			Board = board;
		}

		public void Solve()
		{
			Mask = new int[N, M];

			int Areas = Fill();

			bool[] prepared = new bool[Areas+1];

			for (int i = 1; i <= Areas; i++)
			{
				Graph.Add(i, new Vertex() { V = i });
			}

			for (int i = 0; i < Mask.GetLength(0); i++)
				for (int j = 0; j < Mask.GetLength(1); j++)
				{
					if (!prepared[Mask[i, j]])
					{
						bool[,] walked = new bool[Mask.GetLength(0), Mask.GetLength(1)];
						prepared[Mask[i, j]] = true;
						FillAdjast(walked, i, j);
					}
				}

			int max = -1;

			foreach (var v in Graph)
			{
				//genereate Wave
				bool[] walked2 = new bool[Areas + 1];
				walked2[v.Value.V] = true;
				List<Vertex> wave = new List<Vertex>();
				wave.Add(v.Value);
				bool startBlack = v.Value.Color == 'B';

				if (startBlack && max < 0)
					max = 0;

				bool needBreak;
				for (int i = 1; i < Areas; i++)
				{
					List<Vertex> newWave = new List<Vertex>();
					needBreak = true;
					foreach (var vinwave in wave)
						foreach (var adj in vinwave.Adjast)
							if (!walked2[adj.V])
							{
								walked2[adj.V] = true;
								newWave.Add(adj);
								needBreak = false;
								if (startBlack && adj.Color == 'B' && i > max)
									max = i;
							}
					wave = newWave;
					if (needBreak)
						break;
				}
			}

			Console.WriteLine((max + 2)/2);
		}

		private void FillAdjast(bool[,] walked, int i, int j)
		{
			if (walked[i, j])
				return;

			walked[i, j] = true;
			int c = Mask[i, j];
			Graph[c].Color = Board[i][j];

			if (i > 0)
			{
				if (Mask[i - 1, j] == c)
					FillAdjast(walked, i - 1, j);
				else
					Graph[c].Adjast.Add(Graph[Mask[i - 1, j]]);
			}
			if (j > 0)
			{
				if (Mask[i, j-1] == c)
					FillAdjast(walked, i , j-1);
				else
					Graph[c].Adjast.Add(Graph[Mask[i, j-1]]);
			}
			if (i < N-1)
			{
				if (Mask[i + 1, j] == c)
					FillAdjast(walked, i + 1, j);
				else
					Graph[c].Adjast.Add(Graph[Mask[i + 1, j]]);
			}
			if (j < M-1)
			{
				if (Mask[i , j + 1] == c)
					FillAdjast(walked, i , j + 1);
				else
					Graph[c].Adjast.Add(Graph[Mask[i, j + 1]]);
			}
		}

		private int Fill()
		{
			int k = 1;
			for (int i = 0; i < Mask.GetLength(0); i++)
				for (int j = 0; j < Mask.GetLength(1); j++)
					if (Mask[i, j] == 0)
					{
						FillPart(i, j, k);
						k++;
					}
			return k - 1;
		}

		private void FillPart(int i, int j, int k)
		{
			char c = Board[i][j];
			Mask[i, j] = k;

			if (i > 0 && Mask[i - 1, j] == 0 && Board[i - 1][j] == c)
				FillPart(i - 1, j, k);

			if (j > 0 && Mask[i, j - 1] == 0 && Board[i][j - 1] == c)
				FillPart(i, j - 1, k);

			if (i < Mask.GetLength(0)-1 && Mask[i + 1, j] == 0 && Board[i + 1][j] == c)
				FillPart(i + 1, j, k);

			if (j < Mask.GetLength(1)-1 && Mask[i, j + 1] == 0 && Board[i][j + 1] == c)
				FillPart(i, j + 1, k);
		}
	}

	class Program
	{
		//static StreamReader inStream = new StreamReader("input.txt");
		//static string ReadLine()
		//{
		//    return inStream.ReadLine();
		//}

		static string ReadLine()
		{
			return Console.ReadLine();
		}

		static void Main(string[] args)
		{
			string[] arg1 = ReadLine().Split();
			int N = int.Parse(arg1[0]);
			int M = int.Parse(arg1[1]);

			string[] board = new string[N];

			for (int i = 0; i < N; i++)
			{
				board[i] = ReadLine();
			}

			new Solver(N, M, board).Solve();
		}

	}
}

Having unraveled the Berland Dictionary, the scientists managed to read the notes of the chroniclers of that time. For example, they learned how the chief of the ancient Berland tribe was chosen.As soon as enough pretenders was picked, the following test took place among them: the chief of the tribe took a slab divided by horizontal and vertical stripes into identical squares (the slab consisted of N lines and M columns) and painted every square black or white. Then every pretender was given a slab of the same size but painted entirely white. Within a day a pretender could paint any side-linked set of the squares of the slab some color. The set is called linked if for any two squares belonging to the set there is a path belonging the set on which any two neighboring squares share a side. The aim of each pretender is to paint his slab in the exactly the same way as the chief’s slab is painted. The one who paints a slab like that first becomes the new chief.Scientists found the slab painted by the ancient Berland tribe chief. Help them to determine the minimal amount of days needed to find a new chief if he had to paint his slab in the given way.

The first line contains two integers N and M (1 ≤ N, M ≤ 50) — the number of lines and columns on the slab. The next N lines contain M symbols each — the final coloration of the slab. W stands for the square that should be painted white and B — for the square that should be painted black.

In the single line output the minimal number of repaintings of side-linked areas needed to get the required coloration of the slab.

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

namespace _37E
{
	class Vertex
	{
		public int V;
		public char Color;
		public HashSet<Vertex> Adjast = new HashSet<Vertex>();

		public override string ToString()
		{
			return V.ToString() + "(" + Color + ")";
		}
	}

	class Solver
	{
		public int N { get; set; }
		public int M { get; set; }
		public string[] Board { get; set; }
		int[,] Mask;
		Dictionary<int, Vertex> Graph = new Dictionary<int, Vertex>();

		public Solver(int N, int M, string[] board)
		{
			this.N = N;
			this.M = M;
			Board = board;
		}

		public void Solve()
		{
			Mask = new int[N, M];

			int Areas = Fill();

			bool[] prepared = new bool[Areas+1];

			for (int i = 1; i <= Areas; i++)
			{
				Graph.Add(i, new Vertex() { V = i });
			}

			for (int i = 0; i < Mask.GetLength(0); i++)
				for (int j = 0; j < Mask.GetLength(1); j++)
				{
					if (!prepared[Mask[i, j]])
					{
						bool[,] walked = new bool[Mask.GetLength(0), Mask.GetLength(1)];
						prepared[Mask[i, j]] = true;
						FillAdjast(walked, i, j);
					}
				}

			int min = int.MaxValue;

			foreach (var v in Graph)
			{
				//genereate Wave
				bool[] walked2 = new bool[Areas + 1];
				walked2[v.Value.V] = true;
				List<Vertex> wave = new List<Vertex>();
				wave.Add(v.Value);
				bool startBlack = v.Value.Color == 'B';

				int max = -1;

				if (startBlack && max < 0)
					max = 0;

				bool needBreak;
				for (int i = 1; i < Areas; i++)
				{
					List<Vertex> newWave = new List<Vertex>();
					needBreak = true;
					foreach (var vinwave in wave)
						foreach (var adj in vinwave.Adjast)
							if (!walked2[adj.V])
							{
								walked2[adj.V] = true;
								newWave.Add(adj);
								needBreak = false;
								if (adj.Color == 'B' && i > max)
									max = i;
							}
					wave = newWave;
					if (needBreak)
						break;
				}

				if (min > max)
					min = max;
			}

			Console.WriteLine(min + 1);
		}

		private void FillAdjast(bool[,] walked, int i, int j)
		{
			if (walked[i, j])
				return;

			walked[i, j] = true;
			int c = Mask[i, j];
			Graph[c].Color = Board[i][j];

			if (i > 0)
			{
				if (Mask[i - 1, j] == c)
					FillAdjast(walked, i - 1, j);
				else
					Graph[c].Adjast.Add(Graph[Mask[i - 1, j]]);
			}
			if (j > 0)
			{
				if (Mask[i, j-1] == c)
					FillAdjast(walked, i , j-1);
				else
					Graph[c].Adjast.Add(Graph[Mask[i, j-1]]);
			}
			if (i < N-1)
			{
				if (Mask[i + 1, j] == c)
					FillAdjast(walked, i + 1, j);
				else
					Graph[c].Adjast.Add(Graph[Mask[i + 1, j]]);
			}
			if (j < M-1)
			{
				if (Mask[i , j + 1] == c)
					FillAdjast(walked, i , j + 1);
				else
					Graph[c].Adjast.Add(Graph[Mask[i, j + 1]]);
			}
		}

		private int Fill()
		{
			int k = 1;
			for (int i = 0; i < Mask.GetLength(0); i++)
				for (int j = 0; j < Mask.GetLength(1); j++)
					if (Mask[i, j] == 0)
					{
						FillPart(i, j, k);
						k++;
					}
			return k - 1;
		}

		private void FillPart(int i, int j, int k)
		{
			char c = Board[i][j];
			Mask[i, j] = k;

			if (i > 0 && Mask[i - 1, j] == 0 && Board[i - 1][j] == c)
				FillPart(i - 1, j, k);

			if (j > 0 && Mask[i, j - 1] == 0 && Board[i][j - 1] == c)
				FillPart(i, j - 1, k);

			if (i < Mask.GetLength(0)-1 && Mask[i + 1, j] == 0 && Board[i + 1][j] == c)
				FillPart(i + 1, j, k);

			if (j < Mask.GetLength(1)-1 && Mask[i, j + 1] == 0 && Board[i][j + 1] == c)
				FillPart(i, j + 1, k);
		}
	}

	class Program
	{
		//static StreamReader inStream = new StreamReader("input.txt");
		//static string ReadLine()
		//{
		//    return inStream.ReadLine();
		//}

		static string ReadLine()
		{
			return Console.ReadLine();
		}

		static void Main(string[] args)
		{
			string[] arg1 = ReadLine().Split();
			int N = int.Parse(arg1[0]);
			int M = int.Parse(arg1[1]);

			string[] board = new string[N];

			for (int i = 0; i < N; i++)
			{
				board[i] = ReadLine();
			}

			new Solver(N, M, board).Solve();
		}

	}
}


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

public class Program
{
    public static void Main(string[] args)
    {
        var input = Console.ReadLine();

        System.Console.WriteLine(Solve(input));
    }

    private static string Solve(string input)
    {
        var n = input.Length;
        if (n % 2 != 0)
        {
            return Generate(0, String.Empty, n + 1);
        }

        var result = new char[n];
        var foors = 0;
        var sevens = 0;
        for (int i = 0; i < n; ++i)
        {
            if (input[i] < '4')
            {
                var prefix = new string(result, 0, i);
                if (foors < n / 2)
                {
                    prefix = prefix + '4';
                    ++foors;
                }
                else
                {
                    prefix = prefix + '7';
                }
                return Generate(foors, prefix, n);
            }

            if (input[i] == '4')
            {
                if (foors < n / 2)
                {
                    result[i] = '4';
                    ++foors;
                    continue;
                }
                else
                {
                    result[i] = '7';
                    return Generate(foors, new string(result, 0, i + 1), n);
                }
            }

            if (input[i] < '7')
            {
                if (sevens < n / 2)
                {
                    var prefix = new string(result, 0, i) + '7';
                    return Generate(foors, prefix, n);
                }
                return FindLeft(input, result, i - 1, sevens, foors);
            }

            if (input[i] == '7')
            {
                if (sevens < n / 2)
                {
                    result[i] = '7';
                    ++sevens;
                    continue;
                }
                return FindLeft(input, result, i - 1, sevens, foors);
            }

            if (input[i] > '7')
            {
                return FindLeft(input, result, i - 1, sevens, foors);
            }
        }
        return new string(result);
    }

    private static string FindLeft(string input, char[] result, int start, int sevens, int foors)
    {
        int n = input.Length;
        for (int i= start; i >= 0; --i)
        {
            if (result[i] == '7')
            {
                --sevens;
            }
            else
            {
                --foors;
                if (sevens < n / 2)
                {
                    result[i] = '7';
                    return Generate(foors, new string(result, 0, i), n);
                }
            }
        }
        return Generate(0, "", n + 2);
    }

    private static string Generate(int foors, string prefix, int size)
    {
        var realSize = size - prefix.Length;

        return prefix + new String('4', size/2 - foors) +
               new String('7', realSize - size / 2 + foors);
    }
}

Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.

The only line contains a positive integer n (1 ≤ n ≤ 10100000). This number doesn't have leading zeroes.

Output the least super lucky number that is more than or equal to n.

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

namespace ProgrammingContest.Codeforces.Round77
{
    class B
    {
        static string s;
        static char[] cs;
        static char[] val = new char[2] { '4', '7' };
        static bool dfs2(int i, int c4, int c7, bool eq)
        {
            if (i >= s.Length)
                return c4 == c7;
            for (int j = 0; j < 2; j++)
            {
                if (eq && val[j] < s[i])
                    continue;
                cs[i] = val[j];
                if (dfs2(i + 1, c4 + 1 - j, c7 + j, eq && s[j] == cs[i]))
                    return true;
            }
            return false;
        }
        static bool dfs()
        {
            Stack<char> sc = new Stack<char>();
            Stack<int> si = new Stack<int>();
            Stack<int> s4 = new Stack<int>();
            Stack<int> s7 = new Stack<int>();
            Stack<bool> seq = new Stack<bool>();

            si.Push(0);
            s4.Push(0);
            s7.Push(0);
            seq.Push(true);

            while (si.Any())
            {
                int i = si.Pop(),
                    c4 = s4.Pop(),
                    c7 = s7.Pop();
                if (i > 0) cs[i - 1] = sc.Pop();
                bool eq = seq.Pop();
                if (Math.Min(c4, c7) + s.Length - i < Math.Max(c4, c7))
                    continue;
                if (i >= s.Length)
                {
                    if (c4 == c7)
                        return true;
                    continue;
                }
                for (int j = 1; j >= 0; j--)
                {
                    if (eq && val[j] < s[i])
                        continue;
                    sc.Push(val[j]);
                    si.Push(i + 1);
                    s4.Push(c4 + 1 - j);
                    s7.Push(c7 + j);
                    seq.Push(eq && s[i] == val[j]);
                }
            }
            return false;
        }

        public static void Main()
        {
            s = Console.ReadLine();
            cs = s.ToCharArray();
            if (s.Length%2 == 0 && dfs())
                Console.WriteLine(new string(cs));
            else
            {
                int len = s.Length;
                if (len % 2 == 0) len = len / 2 + 1;
                else if (len % 2 == 1) len = (len + 1) / 2;
                for (int i = 0; i < len * 2; i++)
                    Console.Write(i < len ? '4' : '7');
                Console.WriteLine();
            }
            return;
            for (int t = 7700; t <= 7900; t++)
            {
                //s = '1' + "".PadLeft(99999, '0');
                Console.Write(t + ":");
                s = t.ToString();
                cs = s.ToCharArray();
                if (dfs())
                    Console.WriteLine(new string(cs));
                else
                {
                    int len = s.Length;
                    if (len % 2 == 0) len = len / 2 + 2;
                    if (len % 2 == 1) len = (len + 1) / 2;
                    for (int i = 0; i < len * 2; i++)
                        Console.Write(i < len ? '4' : '7');
                    Console.WriteLine();
                }
            }
        }
    }
}


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

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

        private static void Main(string[] args)
        {
            string s = reader.ReadLine();
            s = "*" + reader.ReadLine() + "*";
            string t = "*" + reader.ReadLine() + "*";

            int n = s.Length - 2;
            if (Op(s[n - 1]) == t[n - 1])
            {
                writer.WriteLine("NO");
                writer.Flush();
                return;
            }

            int index2 = 1;
            int index1 = 1;

            int p1 = 1;
            int p2 = 1;

            for (int i = 0; i < 10; i++)
            {
                for (; index1 < n; index1++)
                {
                    if (t[index2] == s[index1])
                        index2++;
                    else if (t[index2 - 1] == Op(s[index1]))
                        index2--;
                }

                if (index2 == n)
                {
                    writer.WriteLine("YES");
                    writer.Flush();
                    return;
                }

                for (; index2 < n; index2++)
                {
                    if (t[index2] == s[index1])
                        index1++;
                    else if (s[index1 - 1] == Op(t[index2]))
                        index1--;
                }

                if (index1 == n)
                {
                    writer.WriteLine("YES");
                    writer.Flush();
                    return;
                }

                if (p1 == index1 || p2 == index2)
                {
                    break;
                }

                p1 = index1;
                p2 = index2;
            }

            writer.WriteLine("NO");
            writer.Flush();
        }

        private static char Op(char c)
        {
            switch (c)
            {
                case 'N':
                    return 'S';
                case 'S':
                    return 'N';
                case 'W':
                    return 'E';
                case 'E':
                    return 'W';
            }
            return '1';
        }
    }
}

In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.

The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths. The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW". The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path.

Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.

NoteIn the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.In the second sample, no sequence of moves can get both marbles to the end.

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

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

        private static void Main(string[] args)
        {
            reader.ReadLine();
            List<char> s = reader.ReadLine().ToCharArray().ToList();
            s.Reverse();
            for (int i = 0; i < s.Count; i++)
            {
                s[i] = Op(s[i]);
            }

            s.AddRange(reader.ReadLine().ToCharArray());

            var pi = new int[s.Count];

            for (int i = 1; i < s.Count; ++i)
            {
                int j = pi[i - 1];
                while (j > 0 && s[i] != s[j])
                    j = pi[j - 1];
                if (s[i] == s[j]) ++j;
                pi[i] = j;
            }

            writer.WriteLine(pi[pi.Length - 1] == 0 ? "YES" : "NO");
            writer.Flush();
        }

        private static char Op(char c)
        {
            switch (c)
            {
                case 'N':
                    return 'S';
                case 'S':
                    return 'N';
                case 'W':
                    return 'E';
                case 'E':
                    return 'W';
            }
            return '1';
        }
    }
}


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

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

        private static void Main(string[] args)
        {
            int n = Next();
            int m = Next();

            var nn = new int[n + 1];
            var op = new int[m];
            var id = new int[m];

            for (int i = 0; i < m; i++)
            {
                op[i] = Next();
                id[i] = Next();

                if (op[i] == 1)
                {
                    if (nn[id[i]] == 0)
                    {
                        nn[id[i]] = 1;
                    }
                }
                else
                {
                    if (nn[id[i]] == 0)
                    {
                        nn[id[i]] = 2;
                    }
                }
            }

            for (int i = 1; i < nn.Length; i++)
            {
                if (nn[i] == 0)
                    nn[i] = 3;
            }

            int count2 = nn.Count(t => t == 2);

            if (count2 == 0)
            {
                int id3 = id[0];
                int count3 = 1;
                bool ok = true;
                for (int i = 1; i < m; i++)
                {
                    if (op[i] == 1)
                    {
                        count3++;
                        if (count3 == 1)
                        {
                            if (id[i] != id3)
                            {
                                ok = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        count3--;
                        if (count3 == 0)
                        {
                            if (id[i] != id3)
                            {
                                ok = false;
                                break;
                            }
                        }
                    }
                }
                if (ok)
                {
                    nn[id3] = 3;
                }
            }
            else
            {
                for (int i = 1; i <= n; i++)
                {
                    if (nn[i] == 2)
                    {
                        nn[i] = 3;
                    }
                }
                int id4 = -1;
                for (int i = 0; i < m; i++)
                {
                    if (op[i] == 1)
                    {
                        count2++;
                        if (count2 == 1)
                        {
                            if (id4 >= 0)
                            {
                                if (id[i] != id4)
                                    id4 = -2;
                            }
                        }
                    }
                    else
                    {
                        count2--;
                        if (nn[id[i]] == 3)
                            nn[id[i]] = 2;
                        if (count2 == 0)
                        {
                            if (nn[id[i]] == 2)
                            {
                                if (id4 == -1)
                                    id4 = id[i];
                                else
                                {
                                    if (id4 != id[i])
                                    {
                                        id4 = -2;
                                    }
                                }
                            }
                            else id4 = -2;
                        }
                    }
                }
                if (id4 > 0)
                    nn[id4] = 3;
            }

            int count = nn.Count(t => t == 3);

            writer.WriteLine(count);

            if (count > 0)
            {
                for (int i = 1; i <= n; i++)
                {
                    if (nn[i] == 3)
                    {
                        writer.Write(i);
                        writer.Write(' ');
                    }
                }
            }

            writer.Flush();
        }

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

Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.One day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.You are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).

The first line contains integers n and m (1 ≤ n, m ≤ 105) — the number of team participants and the number of messages. Each of the next m lines contains a message in the format:   '+ id': the record means that the person with number id (1 ≤ id ≤ n) has logged on to the meeting.  '- id': the record means that the person with number id (1 ≤ id ≤ n) has logged off from the meeting.  Assume that all the people of the team are numbered from 1 to n and the messages are given in the chronological order. It is guaranteed that the given sequence is the correct record of a continuous part of the meeting. It is guaranteed that no two log on/log off events occurred simultaneously.

In the first line print integer k (0 ≤ k ≤ n) — how many people can be leaders. In the next line, print k integers in the increasing order — the numbers of the people who can be leaders. If the data is such that no member of the team can be a leader, print a single number 0.

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

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

        private static void Main(string[] args)
        {
            int n = Next();
            int m = Next();

            var nn = new int[n + 1];
            var op = new int[m];
            var id = new int[m];

            for (int i = 0; i < m; i++)
            {
                op[i] = Next();
                id[i] = Next();

                if (op[i] == 1)
                {
                    if (nn[id[i]] == 0)
                    {
                        nn[id[i]] = 1;
                    }
                }
                else
                {
                    if (nn[id[i]] == 0)
                    {
                        nn[id[i]] = 2;
                    }
                }
            }

            for (int i = 1; i < nn.Length; i++)
            {
                if (nn[i] == 0)
                    nn[i] = 3;
            }

            int count2 = nn.Count(t => t == 2);

            if (count2 == 0)
            {
                int id3 = id[0];
                int count3 = 1;
                bool ok = true;
                for (int i = 1; i < m; i++)
                {
                    if (op[i] == 1)
                    {
                        count3++;
                        if (count3 == 1)
                        {
                            if (id[i] != id3)
                            {
                                ok = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        count3--;
                        if (count3 == 0)
                        {
                            if (id[i] != id3)
                            {
                                ok = false;
                                break;
                            }
                        }
                        else if (id[i] == id3)
                        {
                            ok = false;
                            break;
                        }
                    }
                }
                if (ok)
                {
                    nn[id3] = 3;
                }
            }
            else
            {
                for (int i = 1; i <= n; i++)
                {
                    if (nn[i] == 2)
                    {
                        nn[i] = 3;
                    }
                }
                int id4 = -1;
                for (int i = 0; i < m; i++)
                {
                    if (op[i] == 1)
                    {
                        count2++;
                        if (count2 == 1)
                        {
                            if (id4 >= 0)
                            {
                                if (id[i] != id4)
                                    id4 = -2;
                            }
                        }
                    }
                    else
                    {
                        count2--;
                        if (nn[id[i]] == 3)
                            nn[id[i]] = 2;
                        if (count2 == 0)
                        {
                            if (nn[id[i]] == 2)
                            {
                                if (id4 == -1)
                                    id4 = id[i];
                                else
                                {
                                    if (id4 != id[i])
                                    {
                                        id4 = -2;
                                    }
                                }
                            }
                            else id4 = -2;
                        }
                    }
                }
                if (id4 > 0)
                    nn[id4] = 3;
            }

            int count = nn.Count(t => t == 3);

            writer.WriteLine(count);

            if (count > 0)
            {
                for (int i = 1; i <= n; i++)
                {
                    if (nn[i] == 3)
                    {
                        writer.Write(i);
                        writer.Write(' ');
                    }
                }
            }

            writer.Flush();
        }

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


using System;
using System.Collections.Generic;
using System.Linq;
struct block {public int size { get; set; }public int offset { get; set; }public int index { get; set; }}
class P {
    static int _memory_size;
    static List<block> _memory = new List<block>();
    static int _global_index = 0;
    static void Main() {
        var input = Console.ReadLine().Split().Select(int.Parse);
        int t = input.First(), i = 0;
        _memory_size = input.Last();
        for (; i < t; ++i) {
            var row = Console.ReadLine().Split();
            string type = row[0];
            switch (type) {
                case "alloc": {
                        alloc(int.Parse(row[1]));
                        break;
                    }
                case "defragment": {
                        defragment();
                        break;
                    }
                case "erase": {
                        erase(int.Parse(row[1]));
                        break;
                    }
            }
        }
    }

    static void defragment() {
        int cnt = _memory.Count, i = 0;
        for (; i < cnt; i++) {
            block block = _memory[i];
            if (i == 0) {
                block.offset = 0;
            } else { var prev_block = _memory[i - 1]; block.offset = prev_block.offset + prev_block.size; }
        }
    }

    static void erase(int index) {
        var block = find_block(index);
        if (block.HasValue) {_memory.Remove(block.Value);} else { Console.WriteLine("ILLEGAL_ERASE_ARGUMENT"); }
    }

    static block? find_block(int index) {
        var blocks = _memory.Where(x => x.index == index);
        if (blocks.Count() == 0) {
            return null;
        } else { return blocks.First(); }
    }

    static void alloc(int size) {
        var block = insert_block(size);
        if (block.HasValue) {
            block block_ = block.Value;
            Console.WriteLine(block_.index);
            _memory.Add(block_);
            _memory = _memory.OrderBy(x => x.offset).ToList();
        } else { Console.WriteLine("NULL"); }
    }

    static block? insert_block(int size) {
        int found_offset = -1, cnt = _memory.Count, i = 0;
        if (get_first_empty_size(0) >= size) { found_offset = 0; }
        if (found_offset < 0) {
            for (; i < cnt; ++i) {
                var block_seek = _memory[i].offset + _memory[i].size;
                if (get_first_empty_size(block_seek) >= size) { found_offset = block_seek; break; }
            }
        }
        if (found_offset >= 0) {
            _global_index++;
            return new block() {
                index = _global_index,
                offset = found_offset,
                size = size
            };
        }
        return null;
    }

    static int get_first_empty_size(int seek) {
        var blocks = _memory.Where(x => x.offset >= seek);
        return (blocks.Count() == 0 ? _memory_size : blocks.First().offset) - seek;
    }
}

There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:   alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;  erase x — to erase the block with the identifier x;  defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.

The first line of the input data contains two positive integers t and m (1 ≤ t ≤ 100;1 ≤ m ≤ 100), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.

Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.

6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6

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

struct block {
    public int size { get; set; }
    public int offset { get; set; }
    public int index { get; set; }
}

class P {

    static int _memory_size;
    static List<block> _memory = new List<block>();
    static int _global_index = 0;

    static void Main() {
        var input = Console.ReadLine().Split().Select(int.Parse);
        int t = input.First(), i = 0;
        _memory_size = input.Last();
        for (; i < t; ++i) {
            var row = Console.ReadLine().Split();
            string type = row[0];
            switch (type) {
                case "alloc": {
                        alloc(int.Parse(row[1]));
                        break;
                    }
                case "defragment": {
                        defragment();
                        break;
                    }
                case "erase": {
                        erase(int.Parse(row[1]));
                        break;
                    }
            }
        }
    }

    static void defragment() {
        int cnt = _memory.Count, i = 0;
        for (; i < cnt; i++) {
            block block = _memory[i];
            if (i == 0) {
                block.offset = 0;
            } else { var prev_block = _memory[i - 1]; block.offset = prev_block.offset + prev_block.size; }
            _memory[i] = block;
        }
    }

    static void erase(int index) {
        var block = find_block(index);
        if (block.HasValue) {
            _memory.Remove(block.Value);
        } else { Console.WriteLine("ILLEGAL_ERASE_ARGUMENT"); }
    }

    static block? find_block(int index) {
        var blocks = _memory.Where(x => x.index == index);
        if (blocks.Count() == 0) {
            return null;
        } else { return blocks.First(); }
    }

    static void alloc(int size) {
        var block = insert_block(size);
        if (block.HasValue) {
            Console.WriteLine(block.Value.index);
            _memory.Add(block.Value);
            _memory = _memory.OrderBy(x => x.offset).ToList();
        } else { Console.WriteLine("NULL"); }
    }

    static block? insert_block(int size) {
        int found_offset = -1;
        if (get_first_empty_size(0) >= size) { found_offset = 0; }
        if (found_offset < 0) {
            for (int i = 0; i < _memory.Count; i++) {
                var block_seek = _memory[i].offset + _memory[i].size;
                var block_size = get_first_empty_size(block_seek);
                if (block_size >= size) { found_offset = block_seek; break; }
            }
        }
        if (found_offset >= 0) {
            _global_index++;
            return new block() {
                index = _global_index,
                offset = found_offset,
                size = size
            };
        }
        return null;
    }

    static int get_first_empty_size(int seek) {
        var blocks = _memory.Where(x => x.offset >= seek);
        return (blocks.Count() == 0 ? _memory_size : blocks.First().offset) - seek;
    }
}

[{'input': '6 10\r\nalloc 5\r\nalloc 3\r\nerase 1\r\nalloc 6\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\n']}, {'input': '6 1\r\ndefragment\r\nalloc 10\r\nalloc 1\r\nerase -1\r\nerase 1\r\nerase 1\r\n', 'output': ['NULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '14 100\r\nalloc 99\r\nalloc 1\r\nalloc 1\r\nerase 2\r\nalloc 1\r\nerase 4\r\nerase 1\r\nalloc 100\r\nalloc 1\r\nalloc 99\r\ndefragment\r\nerase 4\r\nalloc 100\r\nalloc 99\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n4\r\nNULL\r\nNULL\r\nNULL\r\n']}, {'input': '26 25\r\ndefragment\r\nerase 1\r\nerase -1560200883\r\nalloc 44\r\ndefragment\r\nalloc 75\r\nalloc 22\r\ndefragment\r\nerase 4\r\ndefragment\r\nalloc 57\r\nalloc 53\r\nerase 4\r\nerase -1639632026\r\nerase -2121605039\r\nerase 3\r\nalloc 51\r\nalloc 65\r\ndefragment\r\nerase 2\r\nerase 4\r\nalloc 52\r\nerase 3\r\ndefragment\r\nerase -1842529282\r\nerase 3\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '22 9\r\nerase 1\r\nalloc 6\r\nalloc 65\r\nerase 1\r\nalloc 87\r\nerase -1638927047\r\nalloc 5\r\nerase 2\r\nalloc 70\r\ndefragment\r\nalloc 20\r\nalloc 48\r\nerase -69401977\r\nalloc 20\r\ndefragment\r\nerase 7\r\ndefragment\r\nerase 9\r\nerase 7\r\nerase 4\r\ndefragment\r\nalloc 66\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '12 40\r\nerase 1\r\nalloc 21\r\nalloc 5\r\nalloc 7\r\ndefragment\r\ndefragment\r\nerase 2\r\nalloc 83\r\nerase 4\r\ndefragment\r\nalloc 59\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\n2\r\n3\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '38 18\r\nalloc 72\r\nerase 2\r\nalloc 50\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 43\r\nalloc 41\r\ndefragment\r\ndefragment\r\nalloc 26\r\nalloc 46\r\nalloc 16\r\nalloc 15\r\ndefragment\r\ndefragment\r\nalloc 95\r\nerase 7\r\nerase 7\r\nerase 5\r\nerase 2\r\nerase 9\r\nerase 7\r\nalloc 43\r\ndefragment\r\nerase 7\r\ndefragment\r\nalloc 48\r\nalloc 77\r\nerase 10\r\nerase 11\r\nalloc 16\r\nalloc 84\r\nerase 1\r\ndefragment\r\nalloc 86\r\ndefragment\r\nerase 13\r\n', 'output': ['NULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nNULL\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '37 74\r\nalloc 11\r\ndefragment\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 90\r\nerase 3\r\nerase 2\r\nerase 3\r\nerase 1\r\nerase 1\r\nalloc 38\r\nalloc 19\r\nerase 1\r\nerase 3\r\ndefragment\r\nalloc 93\r\nerase 5\r\nerase 4\r\nalloc 66\r\nalloc 71\r\nerase 5\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 7\r\nalloc 47\r\nerase -95616683\r\nerase 2\r\nalloc 28\r\nalloc 32\r\nerase 11\r\nalloc 50\r\ndefragment\r\ndefragment\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\n5\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 49\r\nerase -751005193\r\ndefragment\r\nalloc 37\r\nalloc 82\r\nerase 3\r\nerase 1\r\nalloc 80\r\nalloc 51\r\ndefragment\r\nalloc 74\r\nerase 1\r\nalloc 91\r\ndefragment\r\ndefragment\r\nalloc 98\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '42 98\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 5\r\nalloc 66\r\ndefragment\r\nerase 3\r\nalloc 53\r\ndefragment\r\nerase 4\r\nerase 2\r\nalloc 70\r\nerase 3\r\ndefragment\r\ndefragment\r\nerase 2\r\nerase 3\r\nerase -1327931832\r\nalloc 93\r\nalloc 64\r\nerase 7\r\nerase 6\r\nerase 3\r\nalloc 61\r\nalloc 12\r\nalloc 65\r\nerase 2\r\nalloc 46\r\nerase 11\r\nerase 9\r\nerase 9\r\nerase 6\r\nalloc 2\r\nalloc 78\r\ndefragment\r\nerase 13\r\nerase 6\r\nerase 10\r\nalloc 53\r\nalloc 46\r\n', 'output': ['1\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '19 46\r\nalloc 21\r\nerase 2\r\nerase 1\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nalloc 40\r\nerase 1\r\ndefragment\r\ndefragment\r\nalloc 68\r\nerase -388966015\r\nalloc 85\r\nalloc 53\r\nerase 4\r\ndefragment\r\nalloc 49\r\nalloc 88\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '44 46\r\nalloc 28\r\nalloc 36\r\ndefragment\r\nerase -937404236\r\nalloc 71\r\ndefragment\r\nalloc 81\r\nalloc 51\r\nerase 3\r\ndefragment\r\nalloc 48\r\nerase 1\r\ndefragment\r\nalloc 36\r\ndefragment\r\ndefragment\r\nerase 1\r\ndefragment\r\ndefragment\r\nerase -1173350787\r\nalloc 94\r\nerase 5\r\ndefragment\r\nerase 9\r\nalloc 98\r\nerase 7\r\ndefragment\r\nerase 5\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nerase 4\r\ndefragment\r\nerase 9\r\nalloc 8\r\ndefragment\r\nerase 9\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 1\r\nalloc 70\r\nerase 9\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '26 25\r\nalloc 25\r\nerase 1\r\nalloc 24\r\nerase 2\r\nalloc 23\r\nerase 3\r\nalloc 24\r\nerase 4\r\nalloc 24\r\nerase 5\r\nalloc 21\r\nerase 6\r\nalloc 24\r\nerase 7\r\nalloc 25\r\nerase 8\r\nalloc 25\r\nerase 9\r\nalloc 24\r\nerase 10\r\nalloc 25\r\nerase 11\r\nalloc 25\r\nerase 12\r\nalloc 25\r\nerase 13\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n']}, {'input': '22 9\r\nalloc 9\r\nerase 1\r\nalloc 9\r\nerase 2\r\nalloc 9\r\nerase 3\r\nalloc 9\r\nerase 4\r\nalloc 9\r\nerase 5\r\nalloc 9\r\nerase 6\r\nalloc 9\r\nerase 7\r\nalloc 9\r\nerase 8\r\nalloc 9\r\nerase 9\r\nalloc 9\r\nerase 10\r\nalloc 9\r\nerase 11\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n']}, {'input': '7 6\r\nalloc 1\r\nalloc 2\r\nalloc 3\r\nerase 1\r\ndefragment\r\nerase 3\r\nalloc 4\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n']}, {'input': '3 1\r\nerase -1\r\nerase 0\r\nerase -2147483648\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '7 100\r\nalloc 100\r\nerase 2147483647\r\nerase 1\r\nalloc 50\r\nalloc 50\r\nerase 3\r\nerase -2147483648\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '12 10\r\nalloc 6\r\nalloc 2\r\nerase 1\r\nalloc 4\r\nalloc 2\r\nerase 3\r\nalloc 2\r\nalloc 3\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\nNULL\r\n6\r\n7\r\n8\r\n9\r\n']}, {'input': '8 50\r\nalloc 51\r\ndefragment\r\nalloc 100\r\ndefragment\r\nerase 1\r\nalloc 50\r\ndefragment\r\nalloc 50\r\n', 'output': ['NULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\n']}, {'input': '10 10\r\nalloc 10\r\nerase -1\r\nerase 1\r\nalloc 5\r\nerase -1\r\nalloc 5\r\nerase 0\r\nalloc 5\r\nerase 0\r\nalloc 5\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\n4\r\n']}]


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

class Program
{
    int mod = 400;
    void solve()
    {
        testIt();
        long n = nextLong();
        long m = nextLong();
        println(fast(n,m));

    }

    private void testIt()
    {
        Random rand = new Random();
        for (int test = 1; ; test++)
        {
            int n = rand.Next() % mod + 1;
            int m = rand.Next() % mod + 1;
            long num = fast(n, m);
            if (num != slow(n, m))
            {
                slow(n, m);
                fast(n, m);
            }

            Console.WriteLine(test + " " + num);
        }
    }

    private long fast(long n, long m)
    {
        long irrational = 0;
        long[] cnt;
        cnt = new long[2*(n + 10)];

        for (long b = 1; b <= n; b++)
        {
            long x = b * b;
            long max = x - 1;
            long min;
            if (m > x)
                min = 0;
            else
                min = x - m;
            long x1=(long)Math.Round(Math.Sqrt(min))-2;
            if (x1 < 0)
                x1 = 0;
            while (x1 * x1 < min)
                x1++;
            long x2=(long)Math.Round(Math.Sqrt(max))+2;
            while (x2 * x2 > max)
                x2--;
            long cur;
            if (x1 <= x2)
                cur = x2 - x1 + 1;
            else
                cur = 0;
            irrational += max - min + 1 - cur;
            if (x1 <= x2)
            {
                x1 += -b;
                x2 += -b;
                x1 = -x1;
                x2 = -x2;
                cnt[x2]++;
                cnt[x1 + 1]--;
            }

            //
            x1 = (long)Math.Round(Math.Sqrt(min)) - 2;
            if (x1 < 0)
                x1 = 0;
            while (x1 * x1 < min)
                x1++;
            x2 = (long)Math.Round(Math.Sqrt(max)) + 2;
            while (x2 * x2 > max)
                x2--;
            if (x1 <= x2)
            {
                x1 = -x1;
                x2 = -x2;
                x1 += -b;
                x2 += -b;
                x1 = -x1;
                x2 = -x2;
                cnt[x1]++;
                cnt[x2 + 1]--;
            }
        }
        irrational *= 2;
        long res = irrational;
        for (int i = 1; i < cnt.Length; i++)
            cnt[i] += cnt[i - 1];
        for (int i = 0; i < cnt.Length; i++)
            if (cnt[i] > 0)
                res++;
        return res;
    }
    long slow(long n, long m)
    {
        long res = 0;
        Dictionary<long, object> d = new Dictionary<long, object>();

        for (long b = 1; b <= n; b++)
            for (long c = 1; c <= m; c++)
            {
                if (b * b - c < 0)
                    continue;
                long del = b * b - c;
                if (!isSquare(del))
                    res += 2;
                else
                {
                    long x = -b + (long)Math.Round(Math.Sqrt(del));
                    d[x] = null;
                    x = -b - (long)Math.Round(Math.Sqrt(del));
                    d[x] = null;
                }
            }
        return res + d.Count;
    }
    private bool isSquare(long n)
    {
        long x =(long)Math.Round( Math.Sqrt(n));
        return x * x == n;
    }

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

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

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

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

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

A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple: x2 + 2bx + c = 0 where b, c are natural numbers.Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover it turned out that several different square equations can have a common root.Petya is interested in how many different real roots have all the equations of the type described above for all the possible pairs of numbers b and c such that 1 ≤ b ≤ n, 1 ≤ c ≤ m. Help Petya find that number.

The single line contains two integers n and m. (1 ≤ n, m ≤ 5000000).

Print a single number which is the number of real roots of the described set of equations.

NoteIn the second test from the statement the following equations are analysed: b = 1, c = 1: x2 + 2x + 1 = 0; The root is x =  - 1 b = 1, c = 2: x2 + 2x + 2 = 0; No roots Overall there's one rootIn the second test the following equations are analysed: b = 1, c = 1: x2 + 2x + 1 = 0; The root is x =  - 1 b = 1, c = 2: x2 + 2x + 2 = 0; No roots b = 1, c = 3: x2 + 2x + 3 = 0; No roots b = 2, c = 1: x2 + 4x + 1 = 0; The roots are  b = 2, c = 2: x2 + 4x + 2 = 0; The roots are  b = 2, c = 3: x2 + 4x + 3 = 0; The roots are x1 =  - 3, x2 =  - 1 b = 3, c = 1: x2 + 6x + 1 = 0; The roots are  b = 3, c = 2: x2 + 6x + 2 = 0; The roots are  b = 3, c = 3: x2 + 6x + 3 = 0; The roots are  Overall there are 13 roots and as the root  - 1 is repeated twice, that means there are 12 different roots.

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

class Program
{
    int mod = 400;
    void solve()
    {
        //testIt();
        long n = nextLong();
        long m = nextLong();
        println(fast(n,m));

    }

    private void testIt()
    {
        Random rand = new Random();
        for (int test = 1; ; test++)
        {
            int n = rand.Next() % mod + 1;
            int m = rand.Next() % mod + 1;
            long num = fast(n, m);
            if (num != slow(n, m))
            {
                slow(n, m);
                fast(n, m);
            }

            Console.WriteLine(test + " " + num);
        }
    }

    private long fast(long n, long m)
    {
        long irrational = 0;
        long[] cnt;
        cnt = new long[2*(n + 10)];

        for (long b = 1; b <= n; b++)
        {
            long x = b * b;
            long max = x - 1;
            long min;
            if (m > x)
                min = 0;
            else
                min = x - m;
            long x1=(long)Math.Round(Math.Sqrt(min))-2;
            if (x1 < 0)
                x1 = 0;
            while (x1 * x1 < min)
                x1++;
            long x2=(long)Math.Round(Math.Sqrt(max))+2;
            while (x2 * x2 > max)
                x2--;
            long cur;
            if (x1 <= x2)
                cur = x2 - x1 + 1;
            else
                cur = 0;
            irrational += max - min + 1 - cur;
            if (x1 <= x2)
            {
                x1 += -b;
                x2 += -b;
                x1 = -x1;
                x2 = -x2;
                cnt[x2]++;
                cnt[x1 + 1]--;
            }

            //
            x1 = (long)Math.Round(Math.Sqrt(min)) - 2;
            if (x1 < 0)
                x1 = 0;
            while (x1 * x1 < min)
                x1++;
            x2 = (long)Math.Round(Math.Sqrt(max)) + 2;
            while (x2 * x2 > max)
                x2--;
            if (x1 <= x2)
            {
                x1 = -x1;
                x2 = -x2;
                x1 += -b;
                x2 += -b;
                x1 = -x1;
                x2 = -x2;
                cnt[x1]++;
                cnt[x2 + 1]--;
            }
        }
        irrational *= 2;
        long res = irrational;
        for (int i = 1; i < cnt.Length; i++)
            cnt[i] += cnt[i - 1];
        for (int i = 0; i < cnt.Length; i++)
            if (cnt[i] > 0)
                res++;
        return res;
    }
    long slow(long n, long m)
    {
        long res = 0;
        Dictionary<long, object> d = new Dictionary<long, object>();

        for (long b = 1; b <= n; b++)
            for (long c = 1; c <= m; c++)
            {
                if (b * b - c < 0)
                    continue;
                long del = b * b - c;
                if (!isSquare(del))
                    res += 2;
                else
                {
                    long x = -b + (long)Math.Round(Math.Sqrt(del));
                    d[x] = null;
                    x = -b - (long)Math.Round(Math.Sqrt(del));
                    d[x] = null;
                }
            }
        return res + d.Count;
    }
    private bool isSquare(long n)
    {
        long x =(long)Math.Round( Math.Sqrt(n));
        return x * x == n;
    }

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

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

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

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

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


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int Count = int.Parse(Console.ReadLine());
            int[] Numb = new int[10];
            int Sum = 0; bool clow = false;
            String[] Input = Console.ReadLine().Split(' ');
            for (int i = 0; i < Count; i++)
            {
                int t = int.Parse(Input[i]);
                Numb[t]++;
                Sum += t;
            }
            if (Numb[0] != 0)
            {
                for (int i = 9; i > -1; i--)
                {
                    if ((Numb[i] != 0) && (i > 4))
                    {
                        break;
                    }
                    else
                    {
                        if ((Numb[i] > 1) && (i > 0))
                        {
                            break;
                        }
                        else
                        {
                            if (i == 0)
                            {
                                Console.Write(0);
                                clow = true;
                            }
                        }
                    }
                }
                if (clow!=true)
                {
                if ((Sum % 3 != 0) && (Sum > 9))
                {
                    if (Sum % 3 == 1)
                    {
                        bool flag = false;
                        for (int i = 1; i < 10; i += 3)
                        {
                            if (Numb[i] != 0)
                            {
                                Numb[i]--;
                                flag = true;
                                break;
                            }
                        }
                        if (flag != true)
                        {
                            int m = 0;
                            for (int i = 2; i < 10; i += 3)
                            {
                                if (m != 2)
                                {
                                    while ((Numb[i] > 0) || (m != 2))
                                    {
                                        Numb[i]--;
                                        m++;
                                    }
                                }
                                else
                                {
                                    if (m == 2)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (Sum % 3 == 2)
                        {
                            bool flag = false;
                            for (int i = 2; i < 10; i += 3)
                            {
                                if (Numb[i] != 0)
                                {
                                    Numb[i]--;
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag != true)
                            {
                                int m = 0;
                                for (int i = 1; i < 10; i += 3)
                                {
                                    if (m != 2)
                                    {
                                        while ((Numb[i] > 0) || (m != 2))
                                        {
                                            Numb[i]--;
                                            m++;
                                        }
                                    }
                                    else
                                    {
                                        if (m == 2)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    }
                }
                for (int i = 9; i > -1; i--)
                {
                    while (Numb[i] != 0)
                    {
                        Console.Write(i);
                        Numb[i]--;
                    }
                }
            }
            else
            {
                if (clow == false)
                {
                    Console.Write(-1);
                }
            }

        }
    }
}

Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

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

namespace Solution
{
    class Solution
    {
        public void Solve()
        {
            var n = int.Parse(Console.ReadLine());

            var list = new List<int>();
            {
                var ds = Console.ReadLine().Split(' ');
                foreach (var v in ds)
                {
                    var d = int.Parse(v);
                    list.Add(d);
                }
            }

            if (!list.Contains(0))
            {
                Console.WriteLine("-1");
                return;
            }
            list.Remove(0);

            if (list.Sum() % 3 == 0)
            {
                _o(list);
                return;
            }

            for (int i = 1; i <= 9; i++)
            {
                if (!list.Contains(i))
                    continue;

                if ((list.Sum() - i) % 3 == 0)
                {
                    list.Remove(i);
                    _o(list);
                    return;
                }
            }

            for (int i = 1; i <= 9; i++)
            {
                if (!list.Contains(i))
                    continue;

                list.Remove(i);

                for (int j = 1; j <= i; j++)
                {
                    if (!list.Contains(j))
                        continue;

                    if ((list.Sum() -j) % 3 == 0)
                    {
                        list.Remove(j);
                        _o(list);
                        return;
                    }
                }

                list.Add(i);
            }

            Console.WriteLine("-1");
        }

        void _o(List<int> ds)
        {
            if (ds.Sum() != 0)
            {
                ds.Sort();
                ds.Reverse();
                foreach (var v in ds)
                {
                    Console.Write(v);
                }
            }
            Console.WriteLine("0");
        }

#if !DEBUG
    static void Main(string[] args)
    {
        new Solution().Solve();
    }
#endif
    }
}