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

namespace CodeForce97
{
	class ClassD
	{
		static void Main(string[] args)
		{
			int n = int.Parse(Console.ReadLine());
			int[,] a = new int[100500, 2];

			string[] s;

			for (int i = 0; i < n; i++)
			{
				s = Console.ReadLine().Split(' ');
				a[i, 0] = int.Parse(s[0]);
				a[i, 1] = int.Parse(s[1]);
			}

			Dictionary<int, long[]> d = new Dictionary<int, long[]>();
			for (int i = 0; i < n; i++)
			{
				if (a[i, 0] == a[i, 1])
				{
					if (!d.Keys.Contains(a[i, 0]))
						d.Add(a[i, 0], new long[3]);
					d[a[i, 0]][0]++;
				}
				else
				{
					if (!d.Keys.Contains(a[i, 0]))
						d.Add(a[i, 0], new long[3]);
					if (!d.Keys.Contains(a[i, 1]))
						d.Add(a[i, 1], new long[3]);

					d[a[i, 0]][1]++;
					d[a[i, 1]][2]++;
				}
			}
			long n2 = (n+1) / 2;
			long ans = long.MaxValue;
			foreach (var v in d.Values)
			{
				if (v[0] + v[1] + v[2] < n2)
					continue;

				if (v[0] + v[1] >= n2)
				{
					ans = 0;
					break;
				}
				long ans1 = n2 - v[0] - v[1];
				if (ans1<ans)
					ans = ans1;
			}
			if (ans == long.MaxValue)
				ans = -1;
			Console.WriteLine(ans);

//			Console.ReadKey();
		}
	}

}

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

public class taskA
{
    static void Main(string[] args)
    {
        string inp = Console.ReadLine();
        int n = int.Parse(inp);
        if (n <= 2) { Console.WriteLine("0"); return; }

        int[] cards = new int[n * 2];
        int[] diffcards = new int[n * 2];
        int idx = 0;
        for (int i = 0; i < n; i++)
        {
            inp = Console.ReadLine();
            string[] spl = inp.Split(' ');

            int face = int.Parse(spl[0]);
            int back = int.Parse(spl[1]);
            cards[i * 2] = face;
            cards[i * 2 + 1] = back;
            if (face == back)
            {
                diffcards[idx] = face;

            }
            else
            {
                diffcards[idx] = face;
                idx++;
                diffcards[idx] = back;
            }
            idx++;
        }

        Array.Resize(ref diffcards, idx);

        Random rnd = new Random(Environment.TickCount);

        for (int i = 0; i < 10000; i++)
        {
            int a = rnd.Next(diffcards.Length);
            int b = rnd.Next(diffcards.Length);
            int t = diffcards[a];
            diffcards[a] = diffcards[b];
            diffcards[b] = t;
        }
        Array.Sort(diffcards);
        idx = 0;
        int len=0;

        List<int> candidates = new List<int>();

        while (idx < diffcards.Length)
        {
            len = 0;
            while (idx + len < diffcards.Length && diffcards[idx] == diffcards[idx + len])
            {
                len++;
            }
            if (len * 2 >= n)
            {
                candidates.Add(diffcards[idx]);
            }
            idx += len;
        }
        if (candidates.Count == 0)
        {
            Console.WriteLine("-1"); return;
        }

        int res = -1;
        int need = (n-1)/2 + 1;

        foreach (int color in candidates)
        {
            int FaceUp = 0;
            int canFaceUp = 0;
            for (int i = 0; i < n; i++)
            {
                if (cards[i * 2] == color)
                    FaceUp++;
                else
                    if (cards[i * 2 + 1] == color)
                        canFaceUp++;
            }

            if (FaceUp >= need)
            {
                res = 0;
            }
            else
            {
                int x = Math.Min(need - FaceUp, canFaceUp);

                if (FaceUp + x >= need)
                {
                    if (res < 0 || x < res)
                        res = x;
                }
                else
                {
                    // something went wrong
                }
            }
        }
        Console.WriteLine(res);
    }
}

The Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.


using System;
using System.Linq;

namespace CSharp
{
    class _103B
    {
        public static void Main()
        {
            var tokens = Console.ReadLine().Split();

            int n = int.Parse(tokens[0]);
            int m = int.Parse(tokens[1]);

            var cluster = Enumerable.Range(0, n).ToArray();

            for (int i = 0; i < m; i++)
            {
                tokens = Console.ReadLine().Split();

                int x = int.Parse(tokens[0]) - 1;
                int y = int.Parse(tokens[1]) - 1;

                cluster[GetCluster(x, cluster)] = GetCluster(y, cluster);
            }

            Console.WriteLine(n == m && Enumerable.Range(0, n).Select(i => GetCluster(i, cluster)).Distinct().Count() == 1 ? "FHTAGN!" : "NO");
        }

        private static int GetCluster(int x, int[] cluster) => x == cluster[x] ? x : GetCluster(cluster[x], cluster);
    }
}

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

namespace Semanai___DIa4
{
    class Cthulhu
    {
        static int[] par = new int[102];

        public static void Main(string[] args)
        {
            string input1 = Console.ReadLine();
            int n = int.Parse(input1.Split(' ')[0]);
            int m = int.Parse(input1.Split(' ')[1]);

            for (int i=0; i<101; i++) par[i] = i;

            for (int i=0; i<m; i++)
            {
                string input2 = Console.ReadLine();
                int x = int.Parse(input2.Split(' ')[0]);
                int y = int.Parse(input2.Split(' ')[1]);
                unite(x, y);
            }
            bool check = true;

            for (int i=2; i<=n; i++) if (Find(1) != Find(i)) check = false;

            if (n != m) check = false;

            if (check) Console.WriteLine("FHTAGN!");
            else Console.WriteLine("NO");

            //Console.ReadKey();
        }

        public static int Find(int x)
        {
            if (par[x] == x) return x;
            return par[x] = Find(par[x]);
        }

        public static void unite(int x, int y)
        {
            x = Find(x);
            y = Find(y);
            if (x != y) par[x] = y;
        }
    }

}

...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.It is guaranteed that the graph contains no multiple edges and self-loops.


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

    namespace acm
    {
        class Scanner
        {
            public Scanner(Stream inputStream)
            {
                m_inputStreamReader = new StreamReader(inputStream);
            }

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

            public long NextLong()
            {
                return Int64.Parse(NextToken());
            }

            public double NextDouble()
            {
                return Double.Parse(NextToken());
            }

            public string NextLine()
            {
                return m_inputStreamReader.ReadLine();
            }

            public char NextChar()
            {
                return (char)m_inputStreamReader.Read();
            }

            public string NextToken()
            {
                char nextChar = (char)0;
                while (IsDelimeter(nextChar))
                {
                    nextChar = NextChar();
                }

                string result = "";
                while (!IsDelimeter(nextChar))
                {
                    result += nextChar;
                    nextChar = NextChar();
                }

                return result;
            }

            private bool IsDelimeter(char c)
            {
                return c <= 32;
            }
            private StreamReader m_inputStreamReader;
        }

        class Program
        {
            static Scanner input = new Scanner(Console.OpenStandardInput());

            static void Swap<T>(ref T obj1, ref T obj2)
            {
                T temp = obj1;
                obj1 = obj2;
                obj2 = temp;
            }

            static void A()
            {
                int n = input.NextInt();
                var a = new int[n];
                int total = 0;
                for (int i = 0; i < n; ++i)
                {
                    a[i] = input.NextInt();
                    total += a[i];
                }

                int answer = 0;
                for (int i = 0; i < n; ++i)
                {
                    if (total % 2 == a[i] % 2)
                        ++answer;
                }
                Console.WriteLine(answer);

            }

            static int d(int n)
            {
                int result = 1;

                for (int x = 2; x * x <= n; ++x)
                {
                    int deg = 0;
                    while (n % x == 0)
                    {
                        n /= x;
                        ++deg;
                    }
                    result *= (deg + 1);
                }
                if (n != 1)
                    result *= 2;

                return result;
            }

            static void B()
            {
                int n = input.NextInt(), m = input.NextInt();

                var d = new int[n + 1];
                var edges = new KeyValuePair<int,int>[m];
                for (int i = 0; i < m; ++i)
                {
                    int u = input.NextInt();
                    int v = input.NextInt();
                    edges[i] = new KeyValuePair<int,int>(u,v);
                    ++d[u]; ++d[v];
                }

                int answer = -1;

                bool found = true;
                while (found)
                {
                    var newd = (int[])d.Clone();
                    ++answer;
                    found = false;
                    foreach (var edge in edges)
                    {
                        int u = edge.Key;
                        int v = edge.Value;
                        if (d[u] == 1 || d[v] == 1)
                        {
                            --newd[u];
                            --newd[v];
                            found = true;
                        }
                    }
                    d = newd;
                }

                Console.WriteLine(answer);
            }

            static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); }

            static long getCurrent(long last)
            {
                long result = 1;
                if (last <= 3)
                {
                    for (int i = 1; i <= last; ++i)
                        result *= i;
                }
                else
                {
                    long a = last, b = last - 1;
                    result = a * b;
                    for(long n = last - 2; n >= 1; --n)
                        if (gcd(n, a) == 1 && gcd(n, b) == 1)
                        {
                            result *= n;
                            break;
                        }
                }
                return result;
            }

            static long solve(long n)
            {
                long result = 1;

                for (long last = n; last >= 1; --last)
                {
                    if (last * last * last < result)
                        break;
                    long current = getCurrent(last);
                    result = Math.Max(current, result);
                }

                return result;
            }

            static void C()
            {
                //const int MAXP = 1000100;
                //var isPrime = new bool[MAXP];
                //for (int i = 2; i < MAXP; ++i) isPrime[i] = true;
                //var primes = new List<int>();
                //for(int i = 2; i < MAXP; ++i)
                //    if (isPrime[i])
                //    {
                //        primes.Add(i);
                //        for (int j = i + i; j < MAXP; j += i)
                //            isPrime[j] = false;
                //    }
                //int prev = -1;
                //int maxDif = 0;
                //foreach (var p in primes)
                //{
                //    if (prev != -1)
                //        maxDif = Math.Max(maxDif, p - prev);
                //    prev = p;
                //}
                //Console.WriteLine(maxDif);
                int n = input.NextInt();
                Console.WriteLine(solve(n));
            }

            static void Main(string[] args)
            {
                B();
            }
        }
    }

using System;
using System.Collections.Generic;

namespace _129B
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            int index = str.IndexOf(' ');
            int n = Convert.ToInt32(str.Substring(0, index));
            int m = Convert.ToInt32(str.Substring(index));

            List<Schoolboy> sixthGraders = new List<Schoolboy>();

            for (int i = 0; i < n; i++)
            {
                Schoolboy newSchoolboy = new Schoolboy(i);
                sixthGraders.Add(newSchoolboy);
            }

            for (int i = 0; i < m; i++)
            {
                str = Console.ReadLine();
                index = str.IndexOf(' ');
                int a = Convert.ToInt32(str.Substring(0, index));
                int b = Convert.ToInt32(str.Substring(index));

                sixthGraders[b - 1].numbersOfRelatedSchoolboys.Add(a - 1);
                sixthGraders[a - 1].numbersOfRelatedSchoolboys.Add(b - 1);
            }

            bool isOver = false;
            int numberOfGroup = 0;

            List<Schoolboy> tempSixthGraders = new List<Schoolboy>();

            foreach(Schoolboy sixthGrader in sixthGraders)
            {
                Schoolboy temp = (Schoolboy)sixthGrader.Clone();
                tempSixthGraders.Add(temp);
            }

            while (!isOver)
            {
                sixthGraders = new List<Schoolboy>();

                foreach (Schoolboy sixthGrader in tempSixthGraders)
                {
                    Schoolboy temp = (Schoolboy)sixthGrader.Clone();
                    sixthGraders.Add(temp);
                }

                int numberOfRemoves = 0;

                foreach (Schoolboy sixthGrader in sixthGraders)
                {
                    if (sixthGrader.numbersOfRelatedSchoolboys.Count == 1)
                    {
                        ////foreach (int number in sixthGrader.numbersOfRelatedSchoolboys)
                        ////{
                        ////    tempSixthGraders[number].numbersOfRelatedSchoolboys.Remove(sixthGrader.number);
                        ////}

                        foreach(Schoolboy tempSixthGrader in tempSixthGraders)
                        {
                            if (tempSixthGrader.number == sixthGrader.numbersOfRelatedSchoolboys[0])
                            {
                                tempSixthGrader.numbersOfRelatedSchoolboys.Remove(sixthGrader.number);
                                break;
                            }
                        }

                        foreach(Schoolboy tempSixthGrader in tempSixthGraders)
                        {
                            if (tempSixthGrader.number == sixthGrader.number)
                            {
                                tempSixthGraders.Remove(tempSixthGrader);
                                break;
                            }
                        }

                        numberOfRemoves++;
                    }
                }

                if (numberOfRemoves > 0) numberOfGroup++;

                int numberOfRelated = 0;

                foreach (Schoolboy sixthGrader in tempSixthGraders)
                {
                    if (sixthGrader.numbersOfRelatedSchoolboys.Count == 1) numberOfRelated++;
                }

                if ((numberOfRelated == 1 && tempSixthGraders.Count==0) || numberOfRelated == 0) isOver = true;
            }

            Console.WriteLine(numberOfGroup);
        }
    }

    class Schoolboy : ICloneable
    {
        public int number { get; set; }
        public List<int> numbersOfRelatedSchoolboys = new List<int>();

        public Schoolboy(int number)
        {
            this.number = number;
        }

        public object Clone()
        {
            return new Schoolboy(this.number)
            {
                numbersOfRelatedSchoolboys = new List<int>(this.numbersOfRelatedSchoolboys)
            };
        }
    }
}

Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.


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

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

            string[] str = Console.ReadLine().Split(' ');
            int n = Convert.ToInt32(str[0]);
            int k = Convert.ToInt32(str[1]);

            int[] mas = new int[n];
            string[] str1 = Console.ReadLine().Split(' ');

            for (int i = 0; i < n; i++)
            {
                mas[i] = Convert.ToInt32(str1[i]);
            }
            int count = 0;

            while (mas[0] != k)
            {
                for (int i = 0; i < n - 1; i++)
                {
                    if ((mas[i] != mas[i + 1]) && (mas[i] != k)) { mas[i]++; }
                }
                if (mas[n - 1] != k) { mas[n - 1]++;}
                count++;
            }

            Console.Write(count);
        }
    }
}

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

namespace ProgrammingContest.Codeforces.Round59
{
    class B
    {
        public static void Main()
        {
            int[] nk = Array.ConvertAll(Console.ReadLine().Split(' '), sss => int.Parse(sss));
            int n = nk[0], k = nk[1];
            int[] sol = Array.ConvertAll(Console.ReadLine().Split(' '), sss => int.Parse(sss));
            int res = 0;
            for (; ; res++)
            {
                bool updated = false;
                for (int i = 0; i < sol.Length && sol[i] < k; i++)
                {
                    if (i == sol.Length - 1 || sol[i] != sol[i + 1])
                    {
                        sol[i]++;
                        updated = true;
                    }
                }
                if (!updated)
                    break;
            }
            Console.WriteLine(res);
        }
    }
}

In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
             string a=Console.ReadLine();
             int h=0;
             int n=int.Parse(Console.ReadLine());
             for(int i=0;i<a.Length;i++)
             {
                  bool w=false;
                  for(int j=0;j<i;j++)
                  {
                       if(i!=j)
                       {
                            if(a[i]==a[j])
                            w=true;
                       }
                  }
                  if(w==false)
                  h++;
             }
             if(n-h<0)
             {
                  n=0;
                  h=0;
             }
             //Console.WriteLine(h);
             if(n<=a.Length)
             Console.WriteLine(n-h);
             else
             Console.WriteLine("impossible");
        }

    }
}

using System;
// you can also use other imports, for example:
using System.Collections.Generic;
using System.Linq;
public class HelloWorld {

	public static void Main(string[] args)
	{
		var line = Console.ReadLine();
		var n = Convert.ToInt32(Console.ReadLine());
		if (line.Length < n)
		{
			Console.WriteLine("impossible");
			return;
		}

		var distinct = 0;
		var same = 0;
		var counts = new int[26];

		for (var i = 0; i < line.Length; i++)
		{
			var ind = (int)line[i] - 97;
			if (counts[ind] == 0)
				distinct++;
			else
				same++;

			counts[ind]++;

		}
		if (distinct > n)
		{
			Console.WriteLine(0);
			return;
		}
		var need = n - distinct;
		if (need > same)
		{
			Console.WriteLine("impossible");
			return;
		}

		Console.WriteLine(need);

	}

}

Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

[{'input': 'yandex\n6\n', 'output': ['0\n']}, {'input': 'yahoo\n5\n', 'output': ['1\n']}, {'input': 'google\n7\n', 'output': ['impossible\n']}, {'input': 'a\n1\n', 'output': ['0\n']}, {'input': 'z\n2\n', 'output': ['impossible\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\n26\n', 'output': ['14\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\n26\n', 'output': ['12\n']}, {'input': 'a\n3\n', 'output': ['impossible\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\n1\n', 'output': ['0\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\n4\n', 'output': ['1\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\n20\n', 'output': ['18\n']}, {'input': 'swmkwaruyv\n5\n', 'output': ['0\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\n22\n', 'output': ['0\n']}, {'input': 'abcde\n3\n', 'output': ['0\n']}, {'input': 'abb\n1\n', 'output': ['0\n']}, {'input': 'aaaa\n1\n', 'output': ['0\n']}, {'input': 'abcde\n2\n', 'output': ['0\n']}, {'input': 'yandex\n4\n', 'output': ['0\n']}, {'input': 'aaabbbccc\n1\n', 'output': ['0\n']}, {'input': 'abcd\n2\n', 'output': ['0\n']}, {'input': 'asdfgh\n2\n', 'output': ['0\n']}, {'input': 'aab\n1\n', 'output': ['0\n']}, {'input': 'mynameissako\n5\n', 'output': ['0\n']}, {'input': 'abcde\n1\n', 'output': ['0\n']}, {'input': 'abcd\n3\n', 'output': ['0\n']}, {'input': 'abcdef\n2\n', 'output': ['0\n']}, {'input': 'abcdefg\n4\n', 'output': ['0\n']}, {'input': 'abc\n1\n', 'output': ['0\n']}, {'input': 'asdafjsgljdllgjdgkl\n5\n', 'output': ['0\n']}, {'input': 'yaay\n3\n', 'output': ['1\n']}, {'input': 'yaay\n4\n', 'output': ['2\n']}, {'input': 'zzzzzz\n2\n', 'output': ['1\n']}]


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

namespace codeforces
{
    class C
    {
        static string _input =
@"
atob
a
b
";

        #region test

        static List<string> _lines;

        static string ReadLine()
        {
#if DEBUG
            if (_lines == null)
            {
                _lines = new List<string>();
                string[] ss = _input.Replace("\n", "").Split('\r');
                for (int i = 0; i < ss.Length; i++)
                {
                    if (
                        (i == 0 || i == ss.Length - 1) &&
                        ss[i].Length == 0
                        )
                        continue;

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

            string s = null;
            if (_lines.Count > 0)
            {
                s = _lines[0];
                _lines.RemoveAt(0);
            }
            return s;
#else
            return Console.In.ReadLine();
#endif
        }

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

        static void Write(object o)
        {
#if DEBUG
            System.Diagnostics.Trace.Write(o);
#else
            Console.Write(o);
#endif
        }
        #endregion

        static void Main(string[] args)
        {
            string s = ReadLine();
            string s1 = ReadLine();
            string s2 = ReadLine();

            /*
            s = new string('c', 100000);
            s1 = new string('c', 100000);
            s2 = new string('c', 100000);
            */

            bool f1 = false;
            {
                int i = s.IndexOf(s1);
                if (i >= 0)
                {
                    int i2 = s.IndexOf(s2, i + s1.Length);
                    if (i2 >= 0)
                        f1 = true;
                }
            }

            bool f2 = false;
            {
                List<char> cs = new List<char>( s.ToCharArray());
                cs.Reverse();
                string r = new string(cs.ToArray());

                int i = r.IndexOf(s1);
                if (i >= 0)
                {
                    int i2 = r.IndexOf(s2, i + s1.Length);
                    if (i2 >= 0)
                        f2 = true;
                }
            }

            if (f1 && f2)
                Write("both");
            else if (f1)
                Write( "forward");
            else if (f2)
                Write ("backward");
            else
                Write ("fantasy");
        }

        class Mem
        {
            public int adrs;
            public int size;
        }
    }
}

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

namespace ConsoleApplication1
{
    class Program
    {
        static bool inChain(string chain, string first, string second)
        {
            int ind = chain.IndexOf(first);
            if (ind == -1) return false;
            return chain.IndexOf(second, ind + first.Length) != -1;
        }

        static string reverse(string chain)
        {
            string rez = "";
            char[] charar = chain.ToCharArray();
            for (int i = 0; i < chain.Length; i++)
                rez = charar[i] + rez;
            return rez;
        }

        static bool inChainRev(string chain, string first, string second)
        {
            first = reverse(first);
            second = reverse(second);
            int ind = chain.IndexOf(second);
            if (ind == -1) return false;
            return chain.IndexOf(first, ind + second.Length) != -1;
        }

        static void Main(string[] args)
        {

            string mainChain = Console.ReadLine();
            string first = Console.ReadLine();
            string second = Console.ReadLine();
            bool forward = inChain(mainChain, first, second);
            bool backward = inChainRev(mainChain, first, second);
            if (forward && !backward) Console.WriteLine("forward");
            if (!forward && backward) Console.WriteLine("backward");
            if (forward && backward) Console.WriteLine("both");
            if (!forward && !backward) Console.WriteLine("fantasy");
            inChain(mainChain, first, second);
            Console.ReadKey();
        }
    }
}

Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

[{'input': 'atob\na\nb\n', 'output': ['forward\n']}, {'input': 'aaacaaa\naca\naa\n', 'output': ['both\n']}, {'input': 'aaa\naa\naa\n', 'output': ['fantasy\n']}, {'input': 'astalavista\nastla\nlavista\n', 'output': ['fantasy\n']}, {'input': 'abacabadabacaba\nabacaba\nabacaba\n', 'output': ['both\n']}, {'input': 'a\na\na\n', 'output': ['fantasy\n']}, {'input': 'ab\nb\na\n', 'output': ['backward\n']}, {'input': 'aaa\naaaa\naaaa\n', 'output': ['fantasy\n']}, {'input': 'bbabbbbababbaabaabaa\nabb\nbaab\n', 'output': ['forward\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\nbbbb\nbbbbb\n', 'output': ['both\n']}, {'input': 'babaabababaaaababaabababaabababababababbababbbabbaabababaababbaabbababaababaaabababaabbaababaaababaa\nabaabababaa\nabaabbaa\n', 'output': ['forward\n']}, {'input': 'bbbbbbbbbbbbbbbbbbbbbbbbb\nbbbb\nbbbbb\n', 'output': ['both\n']}, {'input': 'aababaaababaabbaabababaaababaabababbaabbabaabababaabbabbbababbababababababaabababaababaaaabababaabab\nabaabababaa\nabaabbaa\n', 'output': ['backward\n']}, {'input': 'aaaa\naaa\naa\n', 'output': ['fantasy\n']}, {'input': 'zzzz\nzz\nzzz\n', 'output': ['fantasy\n']}, {'input': 'zzzz\nzzzz\nzzzz\n', 'output': ['fantasy\n']}, {'input': 'zzzz\nzz\nzz\n', 'output': ['both\n']}, {'input': 'aabaa\naab\nbaa\n', 'output': ['fantasy\n']}, {'input': 'aabaab\naba\nab\n', 'output': ['forward\n']}, {'input': 'aab\nb\naa\n', 'output': ['backward\n']}, {'input': 'abacaba\naca\nba\n', 'output': ['both\n']}]


using System;
using System.IO;
using System.Reflection;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        int nextInt()
        {
            int c = ' ';
            while ((c == (int)' ' || c == (int)'\n' ||
                c == (int)'\t' || c == (int)'\r')
                && c != -1)
            {
                c = Console.Read();
            }
            bool flag = false;
            if (c == '-') flag = true;
            else
                if ((c < '0' || c > '9') && c != '+') return 0;
            int res = 0;
            if (!char.IsDigit((char)c)) c = Console.Read();
            while (char.IsDigit((char)c))
            {
                res = res * 10 + (int)c - (int)'0';
                c = Console.Read();
            }
            if (flag) res = -res;
            return res;
        }

        bool[][] a;
        int[] f;
        int cur, n;

        void combine(bool[] v1, bool[]v2)
        {
            for(int i=0;i<n;i++)
            {
                v1[i]|=v2[i];
            }
        }

        bool[] flag;
        bool[,] m;

        void dfs(int v)
        {
            if (flag[v]) return;
            flag[v] = true;
            if (v < cur) combine(flag, a[v]);
            for (int i = 0; i < n; i++)
            {
                if (m[v, i]) dfs(i);
            }
        }

        void Solve()
        {
            n = nextInt();
            f = new int[n];
            int[] p = new int[n];
            a = new bool[n][];
            flag = new bool[n];
            for (int i = 0; i < n; i++) p[i] = nextInt()-1;
            for (int i = 0; i < n; i++) f[i] = nextInt();
            m = new bool[n, n];
            for (int i = 0; i < n; i++)
            {
                if (i + f[i] < n) m[i, i + f[i]] = m[i + f[i], i] = true;
                if (i - f[i] >= 0) m[i, i - f[i]] = m[i - f[i], i] = true;
            }
            for (cur = 0; cur < n; cur++)
            {
                for (int j = 0; j < n; j++) flag[j] = false;
                dfs(cur);
                a[cur] = new bool[n];
                combine(a[cur], flag);
            }
            for (int i = 0; i < n; i++)
            {
                if (!a[p[i]][i])
                {
                    Console.Write("NO");
                    return;
                }
            }
            Console.Write("YES");
        }

        static void Main(string[] args)
        {
#if MY_SUPER_PUPER_ONLINE_JUDGE
            string strAppDir =
                        Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
            Console.SetIn(new StreamReader(strAppDir + "\\input.txt"));
            Console.SetOut(new StreamWriter(strAppDir + "\\output.txt"));
#endif
            new Program().Solve();
#if MY_SUPER_PUPER_ONLINE_JUDGE
            Console.In.Close();
            Console.Out.Close();
#endif
        }
    }
}

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

namespace Codeforces
{
	public class G
	{
		public static int Main()
		{
			int n = Convert.ToInt32(Console.ReadLine());

			int [] permutation = Console.ReadLine().Split().Select(x => Convert.ToInt32(x)).ToArray();
			int [] favorite = Console.ReadLine().Split().Select(x => Convert.ToInt32(x)).ToArray();

			int [] marker = new int[n];

			int markerCount = 0;
			for (int i = 0; i < n; ++i)
			{
				if (marker[i] != 0) continue;
				++markerCount;
				Queue<int> lmao = new Queue<int>();
				marker[i] = markerCount;
				lmao.Enqueue(i);
				while (lmao.Count > 0)
				{
					int current = lmao.Dequeue();
					for (int j = 0; j < n; ++j)
					{
						if (current == j) continue;
						if (marker[j] == markerCount) continue;
						if ((Math.Abs(current - j) == favorite[current])
						|| (Math.Abs(current - j) == favorite[j]))
						{
							marker[j] = markerCount;
							lmao.Enqueue(j);
						}
					}
				}
			}

//			for (int i = 0; i < n; ++i) Console.Write("{0} ", marker[i]);
//			Console.WriteLine();

			for (int i = 0; i < n; ++i)
			{
				if (marker[i] != marker[permutation[i] - 1])
				{
					Console.Write("NO");
					return 0;
				}
			}
			Console.Write("YES");

			return 0;
		}
	}
}

One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i-j|=di, where di is a favourite number of i-th cell. Cells make moves in any order, the number of moves is unlimited.The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n. You are to determine whether the game could move to this state.


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

namespace rain
{
    class Program
    {
        public static int check(int[] boul)
        {
            if (boul.Length==1)
                return boul[0];
            if (boul.Length==2)
                return Math.Min(boul[0], boul[1]);
            int[,] c = new int[boul.Length, 2];
            c[0, 0] = boul[0];
            c[1,0] = Math.Min(boul[0], boul[1]);
            int i;
            for (i = 2; i < boul.Length; i++)
            {
                c[i, 0] = Math.Min(boul[i], Math.Max(c[i - 1, 0], c[i - 1, 1]));
                c[i, 1] = Math.Min(boul[i], Math.Max(c[i - 2, 0], c[i - 2, 1]));
            }
            return Math.Max(c[boul.Length - 1, 0], c[boul.Length - 1, 1]);

        }
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine()), i;
            int[] boul = new int[n];
            string s = Console.ReadLine();
            string[] tmp = s.Split(' ');;
            for (i = 0; i < n; i++)
                boul[i] = int.Parse(tmp[i]);
            Console.WriteLine(check(boul));
        }
    }
}

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

namespace B2
{
    class Program
    {
        static void Main(string[] args)
        {
            string str;
            int n;
            str = Console.ReadLine();
            n = Int32.Parse(str);
            int[] a = new int[n];
            str = Console.ReadLine();
            string[] strmas = str.Split();
            for (int i = 0; i < n; i++)
                a[i] = Int32.Parse(strmas[i]);

            for (int t = 1; ; t++)
            {
                int cnt = 0;
                for (int i = 0; i < a.Length; i++)
                {
                    a[i]--;
                    if (a[i] < 0)
                        cnt++;
                    else
                        cnt = 0;
                    if (cnt > 1)
                    {
                        Console.WriteLine(t - 1);
                        return;
                    }
                }
                if (a[0] < 0 || a[a.Length - 1] < 0)
                {
                    Console.WriteLine(t - 1);
                    return;
                }
            }

        }

    }
}

In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i<n-1), you can reach the tiles number i+1 or the tile number i+2 from it (if you stand on the tile number n-1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai+1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.


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

namespace task
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			var n = Int32.Parse (Console.ReadLine ());

			var visitors = new HashSet<string> ();

			var max = 0;

			for (var i = 0; i < n; i++) {
				var visit = Console.ReadLine ();

				if (visit.StartsWith ("+")) {
					visit = visit.Replace ("+ ", "");
					visitors.Add (visit);
					if (visitors.Count > max) max = visitors.Count;
				}

				if (visit.StartsWith ("-")) {
					visit = visit.Replace ("- ", "");
					if (visitors.Contains (visit)) {
						visitors.Remove (visit);
					} else {
						max++;
					}
				}
			}

			Console.WriteLine ("{0}", max);
		}
	}
}

Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 10^6. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.


using System;
using System.Collections.Generic;

namespace _7B_Memory_Manager
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ');
            int operations = int.Parse(input[0]);
            int memsize = int.Parse(input[1]);

            var blocksList = new LinkedList<MemoryBlock>();
            var initialBlock = new MemoryBlock(0, memsize);
            blocksList.AddFirst(initialBlock);
            int num = 0;

            for (int i = 0; i < operations; i++)
            {
                string[] line = Console.ReadLine().Split(' ');
                string command = line[0];

                //alloc
                if (command == "alloc")
                {
                    int bytes = int.Parse(line[1]);
                    bool found = false;

                    foreach (var block in blocksList)
                    {
                        if (block.Length >= bytes && block.Number == 0)
                        {
                            num++;
                            var node = blocksList.Find(block);
                            blocksList.AddBefore(node, new MemoryBlock(num, block.Address, bytes));
                            if (block.Length > bytes)
                            {
                                blocksList.AddBefore(node, new MemoryBlock(block.Address + bytes, block.Length - bytes));
                            }
                            blocksList.Remove(node);

                            found = true;
                            Console.WriteLine(num);
                            break;
                        }
                    }

                    if (found == false)
                    {
                        Console.WriteLine("NULL");
                    }
                }

                //erase
                else if (command == "erase")
                {
                    int index = int.Parse(line[1]);
                    bool found = false;

                    foreach (var block in blocksList)
                    {
                        if (block.Number == index && index != 0)
                        {
                            var node = blocksList.Find(block);

                            if ((node == blocksList.First || node.Previous.Value.Number != 0) && (node == blocksList.Last || node.Next.Value.Number != 0))
                            {
                                node.Value.Number = 0;
                            }
                            else if ((node == blocksList.First || node.Previous.Value.Number != 0) && (node != blocksList.Last && node.Next.Value.Number == 0))
                            {
                                node.Next.Value.Address = node.Value.Address;
                                node.Next.Value.Length += node.Value.Length;
                                blocksList.Remove(node);
                            }
                            else if ((node != blocksList.First && node.Previous.Value.Number == 0) && (node == blocksList.Last || node.Next.Value.Number != 0))
                            {
                                node.Previous.Value.Length += block.Length;
                                blocksList.Remove(node);
                            }
                            else
                            {
                                var nextNode = node.Next;
                                node.Previous.Value.Length += (block.Length + nextNode.Value.Length);
                                blocksList.Remove(node);
                                blocksList.Remove(nextNode);
                            }

                            found = true;
                            break;
                        }
                    }

                    if (found == false)
                    {
                        Console.WriteLine("ILLEGAL_ERASE_ARGUMENT");
                    }

                }

                //defragment
                else
                {
                    var blocksToRemove = new List<MemoryBlock>();

                    foreach (var block in blocksList)
                    {
                        if(block.Number == 0)
                        {
                            blocksToRemove.Add(block);
                        }
                    }

                    foreach(var blockToRemove in blocksToRemove)
                    {
                        blocksList.Remove(blockToRemove);
                    }

                    int length = 0;

                    var blocksToUpdate = new List<MemoryBlock>();

                    foreach (var block in blocksList)
                    {
                        var node = blocksList.Find(block);
                        var blockToUpdate = new MemoryBlock(block.Number, length, block.Length);
                        blocksToUpdate.Add(blockToUpdate);
                        length += node.Value.Length;

                        if(node == blocksList.Last)
                        {
                            blocksToUpdate.Add(new MemoryBlock(length, memsize - length));
                        }
                    }

                    blocksList = new LinkedList<MemoryBlock>(blocksToUpdate);

                    if(blocksList.Count == 0)
                    {
                        blocksList.AddFirst(initialBlock);
                    }
                }
            }

            //Console.ReadKey();
        }
    }

    public class MemoryBlock
    {
        public int Number { get; set; }
        public int Address { get; set; }
        public int Length { get; set; }

        public MemoryBlock() { }

        public MemoryBlock(int address, int length)
        {
            Number = 0;
            Address = address;
            Length = length;
        }

        public MemoryBlock(int number, int address, int length)
        {
            Number = number;
            Address = address;
            Length = length;
        }
    }
}

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

namespace codeforces
{
    class C
    {
        static string _input =
@"
6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6
";

        #region test

        static List<string> _lines;

        static string ReadLine()
        {
#if DEBUG
            if (_lines == null)
            {
                _lines = new List<string>();
                string[] ss = _input.Replace("\n", "").Split('\r');
                for (int i = 0; i < ss.Length; i++)
                {
                    if (
                        (i == 0 || i == ss.Length - 1) &&
                        ss[i].Length == 0
                        )
                        continue;

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

            string s = null;
            if (_lines.Count > 0)
            {
                s = _lines[0];
                _lines.RemoveAt(0);
            }
            return s;
#else
            return Console.In.ReadLine();
#endif
        }

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

        static void Write(object o)
        {
#if DEBUG
            System.Diagnostics.Trace.Write(o);
#else
            Console.Write(o);
#endif
        }
        #endregion

        static void Main(string[] args)
        {
            string[] ss = ReadLine().Split(' ');
            int t = int.Parse(ss[0]);
            int m = int.Parse(ss[1]);

            int nextid = 1;
            Dictionary<int, int> id_adrs = new Dictionary<int, int>();

            SortedDictionary<int, Mem> adrs_mem = new SortedDictionary<int, Mem>();

            Dictionary<Mem,int>mem_adrs = new Dictionary<Mem,int>();

            for (int i = 0; i < t; i++)
            {
                ss = ReadLine().Split(' ');

                if (ss[0] == "alloc")
                {
                    int size = int.Parse(ss[1]);

                    int check_adrs = 0;
                    int? new_adrs = null;
                    foreach (int adrs in adrs_mem.Keys)
                    {
                        if (size <= adrs - check_adrs)
                        {
                            new_adrs = check_adrs;
                            break;
                        }
                        check_adrs = adrs+adrs_mem[adrs].size;
                    }
                    if (new_adrs == null && size <= m - check_adrs)
                    {
                        new_adrs = check_adrs;
                    }

                    if (new_adrs.HasValue)
                    {
                        Mem a = new Mem();
                        a.adrs = new_adrs.Value;
                        a.size = size;
                        adrs_mem.Add(a.adrs, a);

                        mem_adrs.Add(a, nextid);

                        id_adrs.Add(nextid, a.adrs);
                        WriteLine(nextid);
                        nextid++;
                    }
                    else
                        WriteLine("NULL");
                }

                else if (ss[0] == "erase")
                {
                    int id = int.Parse(ss[1]);
                    if (id_adrs.ContainsKey(id))
                    {
                        int adrs = id_adrs[id];
                        Mem mem = adrs_mem[adrs];

                        mem_adrs.Remove(mem);
                        adrs_mem.Remove(adrs);
                        id_adrs.Remove(id);
                    }
                    else
                    {
                        WriteLine("ILLEGAL_ERASE_ARGUMENT");
                    }
                }

                else if (ss[0] == "defragment")
                {
                    SortedDictionary<int, Mem> newadrs_mem = new SortedDictionary<int, Mem>();
                    int newadrs = 0;
                    foreach(int adrs in adrs_mem.Keys)
                    {
                        Mem a = adrs_mem[adrs];
                        a.adrs = newadrs;
                        newadrs += a.size;

                        newadrs_mem.Add(a.adrs, a);

                        id_adrs[mem_adrs[a]] = a.adrs;
                    }

                    adrs_mem = newadrs_mem;
                }
            }
        }

        class Mem
        {
            public int adrs;
            public int size;
        }
    }
}

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.

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


using System;
using System.Collections.Generic;
class Sygrob
{
    public int id;
    public int x;
    public int y;
    public bool active=false;
    public bool flag = false;
    public Sygrob from;
    public List<Sygrob> yes = new List<Sygrob>();
    public Sygrob(int id,int x,int y)
    {
        this.id = id;
        this.x = x;
        this.y = y;
    }
}
class Ski
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        List<Sygrob> graph = new List<Sygrob>();
        List<Sygrob> lost = new List<Sygrob>();
        for (int i = 0; i < n; i++)
        {
            string[] input = Console.ReadLine().Split(' ');
            graph.Add(new Sygrob(i, int.Parse(input[0]), int.Parse(input[1])));
        }
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if ((graph[i].x == graph[j].x || graph[i].y == graph[j].y) && j != i)
                {
                    graph[i].yes.Add(graph[j]);
                }
                else
                {
                    if (j != i && i == 0)
                    {
                        lost.Add(graph[j]);
                    }
                }
            }
        }
        if (lost.Count != 0)
        {
            Sygrob root = graph[0];
            Sygrob temp = null;
            while (!root.flag)
            {
                root.active = true;
                if (root.yes.Count == 0)
                {
                    root.flag = true;
                }
                else
                {
                    for (int i = 0; i < root.yes.Count; i++)
                    {
                        if (!root.yes[i].active && !root.yes[i].flag)
                        {
                            temp = root;
                            root = root.yes[i];
                            if (lost.Contains(root))
                            {
                                lost.Remove(root);
                            }
                            root.from = temp;
                            break;
                        }
                        if (i == root.yes.Count - 1)
                        {
                            root.flag = true;
                            if (root.from != null)
                                root = root.from;
                            break;
                        }
                    }
                }
            }
            for (int k = 0; k < lost.Count;)
            {
                root = lost[k];
                if (lost[k].flag) k++;
                temp = null;
                while (!root.flag)
                {
                    root.active = true;
                    if (root.yes.Count == 0)
                    {
                        root.flag = true;
                    }
                    else
                    {
                        for (int i = 0; i < root.yes.Count; i++)
                        {
                            if (!root.yes[i].active && !root.yes[i].flag)
                            {
                                temp = root;
                                root = root.yes[i];
                                if (lost.Contains(root))
                                {
                                    lost.Remove(root);
                                }
                                root.from = temp;
                                break;
                            }
                            if (i == root.yes.Count - 1)
                            {
                                root.flag = true;
                                if (root.from != null)
                                    root = root.from;
                                break;
                            }
                        }
                    }
                }
            }
        }
        Console.WriteLine(lost.Count);
        //Console.ReadLine();
    }
}

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

namespace CSharp
{
    public class _217A
    {
        public static void Main()
        {
            var clusters = new HashSet<Tuple<SortedSet<int>, SortedSet<int>>>();

            for (int n = int.Parse(Console.ReadLine()); n > 0; n--)
            {
                string[] tokens = Console.ReadLine().Split();

                int x = int.Parse(tokens[0]);
                int y = int.Parse(tokens[1]);

                var xCluster = clusters.FirstOrDefault(cluster => cluster.Item1.Contains(x));
                var yCluster = clusters.FirstOrDefault(cluster => cluster.Item2.Contains(y));

                if (xCluster == null)
                {
                    if (yCluster == null)
                    {
                        clusters.Add(new Tuple<SortedSet<int>, SortedSet<int>>(new SortedSet<int> { x }, new SortedSet<int> { y }));
                    }
                    else
                    {
                        yCluster.Item1.Add(x);
                    }
                }
                else
                {
                    if (yCluster == null)
                    {
                        xCluster.Item2.Add(y);
                    }
                    else if (xCluster != yCluster)
                    {
                        clusters.Remove(xCluster);
                        clusters.Remove(yCluster);

                        clusters.Add(new Tuple<SortedSet<int>, SortedSet<int>>(new SortedSet<int>(xCluster.Item1.Concat(yCluster.Item1)), new SortedSet<int>(xCluster.Item2.Concat(yCluster.Item2))));
                    }
                }
            }

            Console.WriteLine(clusters.Count - 1);
        }
    }
}

Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.


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

namespace Codeforce
    {
    class Domino_Effect
        {
        static void Main (string[] args)
            {
            int n = int.Parse (Console.ReadLine ());
            StringBuilder s = new StringBuilder (Console.ReadLine ());
            int rez;
            FindDomino (s, n, out rez);
            Console.WriteLine (rez);
            }

        public static void FindDomino (StringBuilder s, int lenght, out int rez)
            {
            rez = 0;
            int count = 0;
            bool foundLR = false;

            for (int i = 0; i < lenght; i++)
                {
                if (s[i] == 'R')
                    {
                    rez += count;
                    foundLR = true;
                    count = 1;
                    }
                else if (s[i] == 'L' && foundLR)
                    {
                    foundLR = false;
                    if (++count % 2 == 1)
                        rez++;
                    count = 0;
                    }
                else if (s[i] == 'L' && !foundLR)
                    {
                    count = 0;
                    }
                else
                    {
                    count++;
                    }
                }
            if (!foundLR)
                {
                rez += count;
                }
            }
        }
    }

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

namespace code238
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            string s = Console.ReadLine();
            int l = 0, r = 0, kol = 0, ans = 0;
            bool g = false ;

            for (int i = 0; i < n; i++)
            {
                if (s[i] == 'L') l = 1;
                else
                    if (s[i] == 'R') r = 1;
                    else kol++;
                    if (l == 1 && r == 0)
                    {
                        kol = 0;
                        l = 0;
                    }
                    else
                        if (l == 0 && r == 1 && !g)
                        {
                            ans += kol;
                            kol = 0;
                            g = true;
                        }
                        else
                            if (l==1 && r==1)
                        {

                            if (kol % 2 != 0) ans ++;
                            l = 0; r = 0;
                            g = false; kol = 0;
                        }

            }
            if (l==0 && r==0)
            ans += kol;
            Console.WriteLine(ans);
        }
    }
}

Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process. Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!


//#undef DEBUG

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

namespace codeforces
{
    class C
    {
        //  test
        static CodeforcesUtils CF = new CodeforcesUtils(
@"
2 3
1 2
");

        class Solver
        {
            public void Solve()
            {
                string[] ss = CF.ReadLine().Split(' ');
                int n = int.Parse(ss[0]);
                int l = int.Parse(ss[1]);

                List<int> ai = new List<int>();
                ss = CF.ReadLine().Split(' ');
                foreach (string s in ss)
                    ai.Add(int.Parse(s));

                int max = 0;
                for (int d = l; d<=100; d++)
                {
                    int c = 0;
                    foreach (int a in ai)
                    {
                        c += (a / d);
                    }

                    int size = c * d;
                    max = Math.Max(max, size);
                }
                CF.WriteLine(max);

            }
        }

        #region test

        static void Main(string[] args)
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("ru-RU");

            new Solver().Solve();
            CF.Close();
        }

        static void TLE()
        {
            for (; ; ) ;
        }

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

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

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

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

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

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

            string _test_input;

            List<string> _lines;

#if DEBUG
            public CodeforcesUtils(string test_input)
            {
                _test_input = test_input;
            }
#else

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

            public void Close()
            {
                if( _sr!= null)
                    _sr.Close();
                if( _sw != null)
                    _sw.Close();
            }

            System.IO.StreamReader _sr=null;
            System.IO.StreamWriter _sw=null;

        }

        #endregion
    }
}

The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k×d bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers.


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

namespace Codeforces
{
    class Program
    {
        static void Main()
        {
            var input = Console.ReadLine().Trim().Split(' ');
            var n = Int32.Parse(input[0]);
            var m = Int32.Parse(input[1]);

            var index = new int[n][];
            var chars = new string[n];

            for (int i = 0; i < n; i++)
            {
                chars[i] = Console.ReadLine();
                index[i] = new int[m];
            }
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    if (index[i][j] != 1)
                    {
                        for (int k = i + 1; k < n; k++)
                            if (chars[i][j] == chars[k][j])
                                index[i][j] = index[k][j] = 1;
                    }
                    if (index[i][j] != 2)
                    {
                        for (int k = j + 1; k < m; k++)
                            if (chars[i][j] == chars[i][k])
                                index[i][j] = index[i][k] = 2;
                    }
                }
            }
            var output = new List<char>();
            for (int i = 0; i < n; i++)
                for (int j = 0; j < m; j++)
                    if (index[i][j] == 0)
                        output.Add(chars[i][j]);
            Console.WriteLine(new string(output.ToArray()));

        }
    }
}

using System;
using System.Linq;

namespace cf90B
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] nm = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            int n = nm[0]; int m = nm[1];

            char[][] a = new char[n][];

            bool[][] dupl = new bool[n][];

            for (int i = 0; i < n; i++)
            {
                a[i] = Console.ReadLine().ToCharArray();
                dupl[i] = new bool[a[i].Length];
            }

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    char c = a[i][j];

                    for (int k = 0; k < m; k++)
                    {
                        if (a[i][k] == c && k != j)
                        { dupl[i][k] = true; dupl[i][j] = true; }
                    }

                    for (int k = 0; k < n; k++)
                    {
                        if (a[k][j] == c && k != i)
                        { dupl[k][j] = true; dupl[i][j] = true; }
                    }
                }
            }

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    if (!dupl[i][j])
                        Console.Write(a[i][j]);
                }
            }
        }
    }
}

An African crossword is a rectangular table n×m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.

[{'input': '3 3\ncba\nbcd\ncbc\n', 'output': ['abcd']}, {'input': '5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf\n', 'output': ['codeforces']}, {'input': '4 4\nusah\nusha\nhasu\nsuha\n', 'output': ['ahhasusu']}, {'input': '7 5\naabcd\neffgh\niijkk\nlmnoo\npqqrs\nttuvw\nxxyyz\n', 'output': ['bcdeghjlmnprsuvwz']}, {'input': '10 10\naaaaaaaaaa\nbccceeeeee\ncdfffffffe\ncdfiiiiile\ncdfjjjjile\ndddddddile\nedfkkkkile\nedddddddde\ngggggggggg\nhhhhhhhhhe\n', 'output': ['b']}, {'input': '15 3\njhg\njkn\njui\nfth\noij\nyuf\nyfb\nugd\nhgd\noih\nhvc\nugg\nyvv\ntdg\nhgf\n', 'output': ['hkniftjfbctd']}, {'input': '17 19\nbmzbmweyydiadtlcoue\ngmdbyfwurpwbpuvhifn\nuapwyndmhtqvkgkbhty\ntszotwflegsjzzszfwt\nzfpnscguemwrczqxyci\nvdqnkypnxnnpmuduhzn\noaquudhavrncwfwujpc\nmiggjmcmkkbnjfeodxk\ngjgwxtrxingiqquhuwq\nhdswxxrxuzzfhkplwun\nfagppcoildagktgdarv\neusjuqfistulgbglwmf\ngzrnyxryetwzhlnfewc\nzmnoozlqatugmdjwgzc\nfabbkoxyjxkatjmpprs\nwkdkobdagwdwxsufees\nrvncbszcepigpbzuzoo\n', 'output': ['lcorviunqvgblgjfsgmrqxyivyxodhvrjpicbneodxjtfkpolvejqmllqadjwotmbgxrvs']}, {'input': '1 1\na\n', 'output': ['a']}, {'input': '2 2\nzx\nxz\n', 'output': ['zxxz']}, {'input': '1 2\nfg\n', 'output': ['fg']}, {'input': '2 1\nh\nj\n', 'output': ['hj']}, {'input': '1 3\niji\n', 'output': ['j']}, {'input': '3 1\nk\np\nk\n', 'output': ['p']}, {'input': '2 3\nmhw\nbfq\n', 'output': ['mhwbfq']}, {'input': '3 2\nxe\ner\nwb\n', 'output': ['xeerwb']}, {'input': '3 7\nnutuvjg\ntgqutfn\nyfjeiot\n', 'output': ['ntvjggqfnyfjeiot']}, {'input': '5 4\nuzvs\namfz\nwypl\nxizp\nfhmf\n', 'output': ['uzvsamfzwyplxizphm']}, {'input': '8 9\ntjqrtgrem\nrwjcfuoey\nywrjgpzca\nwabzggojv\najqmmcclh\nozilebskd\nqmgnbmtcq\nwakptzkjr\n', 'output': ['mrjcfuyyrjpzabzvalhozilebskdgnbtpzr']}, {'input': '9 3\njel\njws\ntab\nvyo\nkgm\npls\nabq\nbjx\nljt\n', 'output': ['elwtabvyokgmplabqbxlt']}, {'input': '7 6\neklgxi\nxmpzgf\nxvwcmr\nrqssed\nouiqpt\ndueiok\nbbuorv\n', 'output': ['eklgximpzgfvwcmrrqedoiqptdeiokuorv']}, {'input': '14 27\npzoshpvvjdpmwfoeojapmkxjrnk\nitoojpcorxjdxrwyewtmmlhjxhx\ndoyopbwusgsmephixzcilxpskxh\nygpvepeuxjbnezdrnjfwdhjwjka\nrfjlbypoalbtjwrpjxzenmeipfg\nkhjhrtktcnajrnbefhpavxxfnlx\nvwlwumqpfegjgvoezevqsolaqhh\npdrvrtzqsoujqfeitkqgtxwckrl\nxtepjflcxcrfomhqimhimnzfxzg\nwhkfkfvvjwkmwhfgeovwowshyhw\nolchgmhiehumivswgtfyhqfagbp\ntdudrkttpkryvaiepsijuejqvmq\nmuratfqqdbfpefmhjzercortroh\nwxkebkzchupxumfizftgqvuwgau\n', 'output': ['zshdanicdyldybwgclygzrhkayatwxznmicbpvlupfsoewcleploqngsyolceswtyqbpyasmuadbpcehqva']}, {'input': '1 100\nysijllpanprcrrtvokqmmupuptvawhvnekeybdkzqaduotmkfwybqvytkbjfzyqztmxckizheorvkhtyoohbswcmhknyzlgxordu\n', 'output': ['g']}, {'input': '2 100\ngplwoaggwuxzutpwnmxhotbexntzmitmcvnvmuxknwvcrnsagvdojdgaccfbheqojgcqievijxapvepwqolmnjqsbejtnkaifstp\noictcmphxbrylaarcwpruiastazvmfhlcgticvwhpxyiiqokxcjgwlnfykkqdsfmrfaedzchrfzlwdclqjxvidhomhxqnlmuoowg\n', 'output': ['rbe']}, {'input': '3 100\nonmhsoxoexfwavmamoecptondioxdjsoxfuqxkjviqnjukwqjwfadnohueaxrkreycicgxpmogijgejxsprwiweyvwembluwwqhj\nuofldyjyuhzgmkeurawgsrburovdppzjiyddpzxslhyesvmuwlgdjvzjqqcpubfgxliulyvxxloqyhxspoxvhllbrajlommpghlv\nvdohhghjlvihrzmwskxfatoodupmnouwyyfarhihxpdnbwrvrysrpxxptdidpqabwbfnxhiziiiqtozqjtnitgepxjxosspsjldo\n', 'output': ['blkck']}, {'input': '100 1\na\nm\nn\nh\na\nx\nt\na\no\np\nj\nz\nr\nk\nq\nl\nb\nr\no\ni\ny\ni\np\ni\nt\nn\nd\nc\nz\np\nu\nn\nw\ny\ng\ns\nt\nm\nz\ne\nv\ng\ny\nj\nd\nz\ny\na\nn\nx\nk\nd\nq\nn\nv\ng\nk\ni\nk\nf\na\nb\nw\no\nu\nw\nk\nk\nb\nz\nu\ni\nu\nv\ng\nv\nx\ng\np\ni\nz\ns\nv\nq\ns\nb\nw\ne\np\nk\nt\np\nd\nr\ng\nd\nk\nm\nf\nd\n', 'output': ['hlc']}, {'input': '100 2\nhd\ngx\nmz\nbq\nof\nst\nzc\ndg\nth\nba\new\nbw\noc\now\nvh\nqp\nin\neh\npj\nat\nnn\nbr\nij\nco\nlv\nsa\ntb\nbl\nsr\nxa\nbz\nrp\nsz\noi\nec\npw\nhf\njm\nwu\nhq\nra\npv\ntc\ngv\nik\nux\ntz\nbf\nty\ndk\nwo\nor\nza\nkv\nqt\nfa\njy\nbk\nuv\ngk\ncz\nds\nie\noq\nmf\nxn\nql\nxs\nfb\niv\ncj\nkn\nns\nlg\nji\nha\naj\ndg\nfj\nut\nsg\nju\noc\nov\nhe\nnw\nbl\nlp\nbx\nnm\nyq\ncw\nov\nxk\npg\noh\npl\nuo\ngf\nul\n', 'output': ['dvy']}, {'input': '100 3\nruy\nmye\njgp\nscn\nktq\nalx\nmvk\nlpm\nkry\norb\nmpu\nzcv\nlge\nkft\ndzp\ntfb\nhqz\nuur\nhry\nzjx\ncuo\nqqc\ntih\nenj\nvnp\nbwi\nzzh\nhkc\nwdr\nldh\nvel\nizj\nfhb\nqrn\nqpp\nvzs\nlhg\nkee\nlbq\nzhy\nwcl\nyaa\nton\nfly\nkyw\nept\ngwq\ncoe\nopd\neez\nnmx\nnjg\nwhy\nvel\nafq\nnbq\nulx\noxs\nbbo\nyhx\nfmz\nnrg\nnfm\njek\nbeu\ntya\nxgs\nsgg\nnkq\nbbv\nwkd\ntns\nfdt\neox\nobc\neab\nkkj\noub\ngji\nrht\nozv\nysk\nsbt\nflf\npbu\nlxb\npzs\nrzh\ncea\nkmi\nuea\nncc\nzng\nvkn\njhn\njqw\nlqc\nmbt\nlov\ngam\n', 'output': ['tvdiixs']}]


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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var count = Console.ReadLine();
            var heightString = Console.ReadLine();

            var heights = heightString.Split(' ').Select(a => int.Parse(a)).ToArray();

            var msx = MaxSpread(heights);

            Console.WriteLine(msx);
        }

        public static int MaxSpread(int[] heights)
        {
            var maxItems = 1;
            for (int i = 0; i < heights.Length; i++)
            {
                var d = new Dacha(heights, i);
                while (d.Iterate())
                {

                }

                if (d.TotalItems > maxItems)
                {
                    maxItems = d.TotalItems;
                }
            }

            return maxItems;
        }
    }

    public class Dacha
    {
        private readonly int[] _heights;
        private readonly int _start;
        private int currentLeft;
        private int currentRight;
        private int totalItems = 1;

        public Dacha(int[] heights, int start)
        {
            _heights = heights;
            _start = start;
            currentLeft = start;
            currentRight = start;
        }

        public int TotalItems
        {
            get { return totalItems; }
        }

        public bool Iterate()
        {
            var expanded = false;
            if (currentLeft > 0 && _heights[currentLeft] >= _heights[currentLeft - 1])
            {
                totalItems++;
                expanded = true;
                currentLeft--;
            }

            if (currentRight < _heights.Length-1 && _heights[currentRight + 1] <= _heights[currentRight])
            {
                totalItems++;
                expanded = true;
                currentRight++;
            }

            return expanded;
        }

    }
}

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

class Program
{
    public int max(int[] mas, int i)
    {
        int a = i, res = 1;
        while (a > 0 && mas[a] >= mas[a - 1])
        {
            res++;
            a--;
        }
        a = i;
        while (a < mas.Length - 1 && mas[a] >= mas[a + 1])
        {
            res++;
            a++;
        }
        return res;
    }

    static void Main(string[] args)
    {
        Program p = new Program();
        int res = 1;
        int n = int.Parse(Console.ReadLine());
        int[] mas = new int[n];
        string[] w = Console.ReadLine().Split(' ');
        for (int i = 0; i < n; i++)
        {
            mas[i] = int.Parse(w[i]);
        }
        for(int i=0;i<mas.Length;i++)
        {
            if (p.max(mas, i) > res)
                res = p.max(mas, i);
        }
        Console.WriteLine(res);

        //for (int i = 0; i < n; i++)
        //{
        //    a = int.Parse(w[i]);
        //    mas[a]++;
        //}
    }
}

Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1×n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1×5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture: As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.