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

        string ps = Console.ReadLine();
        long[] p = new long[n];
        string[] spl = ps.Split(' ');
        for (int i = 0; i < n; i++)
            p[i] = long.Parse(spl[i]);

        string costs = Console.ReadLine();
        spl = costs.Split(' ');
        long[] c = new long[5];
        for(int i=0; i<5; i++)
            c[i] = long.Parse(spl[i]);

        long balance = 0;
        long[] counts = new long[5];

        for (int i = 0; i < n; i++)
        {
            balance += p[i];

            for (int j = 4; j >= 0; j--)
            {
                if (balance >= c[j])
                {
                    counts[j] += balance / c[j];
                    balance %= c[j];
                }
            }
        }

        for (int i = 0; i < 5; i++)
            Console.Write("{0} ", counts[i]);
        Console.WriteLine();
        Console.WriteLine(balance);
    }
}

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

namespace Temp
{
    struct PointInt
    {
        public long X;

        public long Y;

        public PointInt(long x, long y)
            : this()
        {
            this.X = x;
            this.Y = y;
        }

        public static PointInt operator +(PointInt a, PointInt b)
        {
            return new PointInt(a.X + b.X, a.Y + b.Y);
        }

        public static PointInt operator -(PointInt a, PointInt b)
        {
            return new PointInt(a.X - b.X, a.Y - b.Y);
        }

        public static PointInt operator *(PointInt a, long k)
        {
            return new PointInt(k * a.X, k * a.Y);
        }

        public static PointInt operator *(long k, PointInt a)
        {
            return new PointInt(k * a.X, k * a.Y);
        }

        public bool IsInsideRectangle(long l, long b, long r, long t)
        {
            return (l <= X) && (X <= r) && (b <= Y) && (Y <= t);
        }
    }

    struct LineInt
    {
        public LineInt(PointInt a, PointInt b)
            : this()
        {
            A = a.Y - b.Y;
            B = b.X - a.X;
            C = a.X * b.Y - a.Y * b.X;
        }

        public long A, B, C;

        public bool ContainsPoint(PointInt p)
        {
            return A * p.X + B * p.Y + C == 0;
        }
    }

    class MatrixInt
    {
        private long[,] m_Matrix;

        public int Size
        {
            get
            {
                return m_Matrix.GetLength(0) - 1;
            }
        }

        public long Mod { get; private set; }

        public MatrixInt(int size, long mod = 0)
        {
            m_Matrix = new long[size + 1, size + 1];
            Mod = mod;
        }

        public MatrixInt(long[,] matrix, long mod = 0)
        {
            this.m_Matrix = matrix;
            Mod = mod;
        }

        public static MatrixInt GetIdentityMatrix(int size, long mod = 0)
        {
            long[,] matrix = new long[size + 1, size + 1];

            for (int i = 1; i <= size; i++)
            {
                matrix[i, i] = 1;
            }

            return new MatrixInt(matrix, mod);
        }

        public long this[int i, int j]
        {
            get
            {
                return m_Matrix[i, j];
            }

            set
            {
                m_Matrix[i, j] = value;
            }
        }

        public static MatrixInt operator +(MatrixInt a, MatrixInt b)
        {
            int n = a.Size;
            long mod = Math.Max(a.Mod, b.Mod);
            long[,] c = new long[n, n];
            for (int i = 1; i <= n; i++)
            {
                for (int j = 1; j <= n; j++)
                {
                    c[i, j] = a[i, j] + b[i, j];
                }
            }

            if (mod > 0)
            {
                for (int i = 1; i <= n; i++)
                {
                    for (int j = 1; j <= n; j++)
                    {
                        c[i, j] %= mod;
                    }
                }
            }

            return new MatrixInt(c, mod);
        }

        public static MatrixInt operator *(MatrixInt a, MatrixInt b)
        {
            int n = a.Size;
            long mod = Math.Max(a.Mod, b.Mod);

            long[,] c = new long[n, n];

            for (int i = 1; i <= n; i++)
            {
                for (int j = 1; j <= n; j++)
                {
                    for (int k = 1; k <= n; k++)
                    {
                        c[i, j] += a[i, k] * b[k, j];
                        if (mod > 0)
                        {
                            c[i, j] %= mod;
                        }
                    }
                }
            }

            return new MatrixInt(c, mod);
        }
    }

    static class Algebra
    {
        public static long Phi(long n)
        {
            long result = n;
            for (long i = 2; i * i <= n; i++)
            {
                if (n % i == 0)
                {
                    while (n % i == 0)
                    {
                        n /= i;
                    }

                    result -= result / i;
                }
            }

            if (n > 1)
            {
                result -= result / n;
            }

            return result;
        }

        public static long BinPower(long a, long n, long mod)
        {
            long result = 1;

            while (n > 0)
            {
                if ((n & 1) != 0)
                {
                    result = (result * a) % mod;
                }

                a = (a * a) % mod;
                n >>= 1;
            }

            return result;
        }

        public static class Permutations
        {
            public static int[] GetRandomPermutation(int n)
            {
                int[] p = new int[n];
                for (int i = 0; i < n; i++)
                {
                    p[i] = i;
                }

                Random random = new Random();
                for (int i = n - 1; i > 0; i--)
                {
                    int j = random.Next(i + 1);
                    int tmp = p[i];
                    p[i] = p[j];
                    p[j] = tmp;
                }

                return p;
            }
        }

        public static T[] Shuffle<T>(this T[] array)
        {
            int length = array.Length;
            int[] p = Permutations.GetRandomPermutation(length);
            T[] result = new T[length];
            for (int i = 0; i < length; i++)
            {
                result[i] = array[p[i]];
            }

            return result;
        }

        public static MatrixInt MatrixBinPower(MatrixInt a, long n)
        {
            MatrixInt result = new MatrixInt(a.Size);

            while (n > 0)
            {
                if ((n & 1) != 0)
                {
                    result *= a;
                }

                a *= a;
                n >>= 1;
            }

            return result;
        }

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

        public static long ExtendedGcd(long a, long b, out long x, out long y)
        {
            if (b == 0)
            {
                x = 1;
                y = 0;
                return a;
            }

            long x1;
            long y1;
            long d = ExtendedGcd(b, a % b, out x1, out y1);
            x = y1;
            y = x1 - (a / b) * y1;
            return d;
        }

        public static long Lcm(long a, long b)
        {
            return (a / Gcd(a, b)) * b;
        }

        public static bool[] GetPrimes(int n)
        {
            n = Math.Max(n, 2);
            bool[] prime = new bool[n + 1];
            for (int i = 2; i <= n; i++)
            {
                prime[i] = true;
            }

            for (int i = 2; i * i <= n; i++)
            {
                if (prime[i])
                {
                    if ((long)i * i <= n)
                    {
                        for (int j = i * i; j <= n; j += i)
                        {
                            prime[j] = false;
                        }
                    }
                }
            }

            return prime;
        }

        public static long GetFibonacciNumber(long n, long mod = 0)
        {
            long[,] matrix = new long[,] { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 1 } };

            MatrixInt result = MatrixBinPower(new MatrixInt(matrix, mod), n);

            return result[2, 2];
        }

        public static long[] GetFibonacciSequence(int n)
        {
            long[] result = new long[n];
            result[0] = result[1] = 1;

            for (int i = 2; i < n; i++)
            {
                result[i] = result[i - 1] + result[i - 2];
            }

            return result;
        }

        public static long GetInverseElement(long a, long mod)
        {
            long x, y;
            long g = ExtendedGcd(a, mod, out x, out y);

            if (g != 1)
            {
                return -1;
            }

            return ((x % mod) + mod) % mod;
        }

        public static long[] GetAllInverseElements(long mod)
        {
            long[] result = new long[mod];
            result[1] = 1;
            for (int i = 2; i < mod; i++)
            {
                result[i] = (mod - (((mod / i) * result[mod % i]) % mod)) % mod;
            }

            return result;
        }
    }

    internal static class Reader
    {
        public static void ReadInt(out int a)
        {
            int[] number = new int[1];
            ReadInt(number);
            a = number[0];
        }

        public static void ReadInt(out int a, out int b)
        {
            int[] numbers = new int[2];
            ReadInt(numbers);
            a = numbers[0];
            b = numbers[1];
        }

        public static void ReadInt(out int int1, out int int2, out int int3)
        {
            int[] numbers = new int[3];
            ReadInt(numbers);
            int1 = numbers[0];
            int2 = numbers[1];
            int3 = numbers[2];
        }

        public static void ReadInt(out int int1, out int int2, out int int3, out int int4)
        {
            int[] numbers = new int[4];
            ReadInt(numbers);
            int1 = numbers[0];
            int2 = numbers[1];
            int3 = numbers[2];
            int4 = numbers[3];
        }

        public static void ReadLong(out long a)
        {
            long[] number = new long[1];
            ReadLong(number);
            a = number[0];
        }

        public static void ReadLong(out long a, out long b)
        {
            long[] numbers = new long[2];
            ReadLong(numbers);
            a = numbers[0];
            b = numbers[1];
        }

        public static void ReadLong(out long int1, out long int2, out long int3)
        {
            long[] numbers = new long[3];
            ReadLong(numbers);
            int1 = numbers[0];
            int2 = numbers[1];
            int3 = numbers[2];
        }

        public static void ReadLong(out long int1, out long int2, out long int3, out long int4)
        {
            long[] numbers = new long[4];
            ReadLong(numbers);
            int1 = numbers[0];
            int2 = numbers[1];
            int3 = numbers[2];
            int4 = numbers[3];
        }

        public static void ReadInt(int[] numbers)
        {
            // ReSharper disable PossibleNullReferenceException
            var list = Console.ReadLine().Split();
            // ReSharper restore PossibleNullReferenceException

            int count = Math.Min(numbers.Length, list.Length);

            for (int i = 0; i < count; i++)
            {
                numbers[i] = int.Parse(list[i]);
            }
        }

        public static int[] ReadDigits()
        {
            // ReSharper disable AssignNullToNotNullAttribute
            return Console.ReadLine().Select(x => int.Parse(x.ToString())).ToArray();
            // ReSharper restore AssignNullToNotNullAttribute
        }

        public static void ReadLong(long[] numbers)
        {
            // ReSharper disable PossibleNullReferenceException
            var list = Console.ReadLine().Split();
            // ReSharper restore PossibleNullReferenceException

            int count = Math.Min(numbers.Length, list.Length);

            for (int i = 0; i < count; i++)
            {
                numbers[i] = long.Parse(list[i]);
            }
        }

        public static void ReadDouble(double[] numbers)
        {
            // ReSharper disable PossibleNullReferenceException
            var list = Console.ReadLine().Split();
            // ReSharper restore PossibleNullReferenceException

            int count = Math.Min(numbers.Length, list.Length);

            for (int i = 0; i < count; i++)
            {
                numbers[i] = double.Parse(list[i]);
            }
        }

        public static void ReadDouble(out double a, out double b)
        {
            double[] numbers = new double[2];
            ReadDouble(numbers);
            a = numbers[0];
            b = numbers[1];
        }

        public static void ReadDouble(out double int1, out double int2, out double int3)
        {
            double[] numbers = new double[3];
            ReadDouble(numbers);
            int1 = numbers[0];
            int2 = numbers[1];
            int3 = numbers[2];
        }
    }

    static class MyMath
    {
        public static int GetMinimalPrimeDivisor(int n)
        {
            for (int i = 2; i * i <= n; i++)
            {
                if (n % i == 0)
                {
                    return i;
                }
            }

            return n;
        }

        public static long Sqr(long x)
        {
            return x * x;
        }
    }

    public interface IGraph
    {
        int Vertices  { get; set; }

        IList<int> this[int i] { get; }

        void AddEdge(int u, int v);

        void AddOrientedEdge(int u, int v);
    }

    public class Graph : IGraph
    {
        private List<int>[] m_Edges;

        public int Vertices { get; set; }

        public IList<int> this[int i]
        {
            get
            {
                return this.m_Edges[i];
            }
        }

        public Graph(int vertices)
        {
            this.Vertices = vertices;

            this.m_Edges = new List<int>[vertices];

            for (int i = 0; i < vertices; i++)
            {
                this.m_Edges[i] = new List<int>();
            }
        }

        public void AddEdge(int u, int v)
        {
            this.AddOrientedEdge(u, v);
            this.AddOrientedEdge(v, u);
        }

        public void AddOrientedEdge(int first, int second)
        {
            this.m_Edges[first].Add(second);
        }

        public int[] Bfs(int start)
        {
            int[] d = new int[Vertices];
            for (int i = 0; i < Vertices; i++)
            {
                d[i] = -1;
            }

            Queue<int> queue = new Queue<int>();
            queue.Enqueue(start);
            d[start] = 0;

            while (queue.Count > 0)
            {
                int v = queue.Dequeue();
                foreach (int t in this.m_Edges[v].Where(t => d[t] == -1))
                {
                    queue.Enqueue(t);
                    d[t] = d[v] + 1;
                }
            }

            return d;
        }
    }

    class SimpleSumTable
    {
        private readonly int[,] m_Sum;

        public SimpleSumTable(int n, int m, int[,] table)
        {
            m_Sum = new int[n + 1, m + 1];

            for (int i = 1; i < n + 1; i++)
            {
                for (int j = 1; j < m + 1; j++)
                {
                    m_Sum[i, j] = m_Sum[i, j - 1] + m_Sum[i - 1, j] - m_Sum[i - 1, j - 1] + table[i, j];
                }
            }
        }

        public int GetSum(int l, int b, int r, int t)
        {
            return m_Sum[r, t] - m_Sum[r, b] - m_Sum[l, t] + m_Sum[l, b];
        }
    }

    class SegmentTreeSimpleInt<T>
    {
        public int Size { get; private set; }

        private readonly T[] m_Tree;

        private Func<T, T, T> m_Operation;

        private T m_Null;

        public SegmentTreeSimpleInt(int size, Func<T, T, T> operation, T nullElement, IList<T> array = null)
        {
            this.Size = size;
            this.m_Operation = operation;
            this.m_Null = nullElement;

            m_Tree = new T[4 * size];
            if (array != null)
            {
                this.Build(array, 1, 0, size - 1);
            }
        }

        private void Build(IList<T> array, int v, int tl, int tr)
        {
            if (tl == tr)
            {
                m_Tree[v] = array[tl];
            }
            else
            {
                int tm = (tl + tr) / 2;
                this.Build(array, 2 * v, tl, tm);
                this.Build(array, 2 * v + 1, tm + 1, tr);
                this.CalculateNode(v);
            }
        }

        public T GetSum(int l, int r)
        {
            return GetSum(1, 0, Size - 1, l, r);
        }

        private T GetSum(int v, int tl, int tr, int l, int r)
        {
            if (l > r)
            {
                return m_Null;
            }

            if (l == tl && r == tr)
            {
                return m_Tree[v];
            }

            int tm = (tl + tr) / 2;

            return this.m_Operation(GetSum(2 * v, tl, tm, l, Math.Min(r, tm)),GetSum(2 * v + 1, tm + 1, tr, Math.Max(l, tm + 1), r));
        }

        public void Update(int pos, T newValue)
        {
            Update(1, 0, Size - 1, pos, newValue);
        }

        private void Update(int v, int tl, int tr, int pos, T newValue)
        {
            if (tl == tr)
            {
                m_Tree[v] = newValue;
            }
            else
            {
                int tm = (tl + tr) / 2;
                if (pos <= tm)
                {
                    Update(2 * v, tl, tm, pos, newValue);
                }
                else
                {
                    Update(2 * v + 1, tm + 1, tr, pos, newValue);
                }
                this.CalculateNode(v);
            }
        }

        private void CalculateNode(int v)
        {
            m_Tree[v] = this.m_Operation(m_Tree[2 * v], m_Tree[2 * v + 1]);
        }
    }

    struct Pair<TFirst, TSecond>
    {
        public Pair(TFirst first, TSecond second)
            : this()
        {
            this.First = first;
            this.Second = second;
        }

        public TFirst First { set; get; }

        public TSecond Second { set; get; }
    }

    class Program
    {
        private static StreamReader m_InputStream;

        private static StreamWriter m_OutStream;

        private static void OpenFiles()
        {
            m_InputStream = File.OpenText("input.txt");
            Console.SetIn(m_InputStream);

            m_OutStream = File.CreateText("output.txt");
            Console.SetOut(m_OutStream);
        }

        private static void CloseFiles()
        {
            m_OutStream.Flush();

            m_InputStream.Dispose();
            m_OutStream.Dispose();
        }

        static void Main()
        {
            //OpenFiles();

            new Solution().Solve();

            //CloseFiles();
        }
    }

    internal class Solution
    {
        public void Solve()
        {
            int n;
            Reader.ReadInt(out n);

            long[] p = new long[n];
            Reader.ReadLong(p);

            long[] c = new long[5];
            Reader.ReadLong(c);

            long current = 0;
            long[] ans = new long[5];

            for (int i = 0; i < n; i++)
            {
                current += p[i];
                for (int j = 4; j >= 0; j--)
                {
                    ans[j] += current / c[j];
                    current = current % c[j];
                }
            }

            for (int i = 0; i < 5; i++)
            {
                Console.Write("{0} ", ans[i]);
            }
            Console.WriteLine();
            Console.Write(current);
        }
    }
}

Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1,p2,...,pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.


using System;
class Program{
	static void Main(string[] args){
		string [] line = Console.ReadLine().Split();
		int n = int.Parse(line[0]);
		long x = Int64.Parse(line[1]);
		long y = Int64.Parse(line[2]);
		long p = y - (n - 1);
		if(p < 1 || (p * p) + (n - 1) < x){
			Console.WriteLine(-1);
		}else{
			Console.WriteLine(p);
			while(n-- > 1)
				Console.WriteLine(1);
		}
	}
}

Little Petya loves inequations. Help him find n positive integers a1,a2,...,an, such that the following two conditions are satisfied: a1^2+a2^2+...+an^2≥x a1+a2+...+an≤y


using System;

class CottageVillage {
	public static void Main()
	{
		string[] T = Console.ReadLine().Split();
		bool[] b = new bool[6001];
		int i;
		for (i = 0; i < b.Length; ++i) b[i] = true;
		int n = int.Parse(T[0]);
		int t = int.Parse(T[1]) * 2;

		for (i = 0; i < n; ++i) {
			T = Console.ReadLine().Split();
			int x = int.Parse(T[0]);
			int a = int.Parse(T[1]);
			for (int j = 2 * x - a + 3000; j <= 2 * x + a + 3000; ++j)
				b[j] = false;
		}

		for (i = 0; i < b.Length; ++i)
			if (!b[i]) break;

		int res = 2;
		int c = 1;
		for (; i < b.Length; ++i) {
			if (b[i])
				c++;
			else if (c > 1) {
				if (c > t) res += 2;
				else if (c == t) res++;
				c = 1;
			}
		}
		Console.WriteLine(res);
	}
}

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

namespace Task_15A
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] temp = Console.ReadLine().Split().Select(double.Parse).ToArray();
            double t = temp[1];
            int n = Convert.ToInt32(temp[0]),ans=2;
            //double[,] cont = new double[n, 2];  //ჩვეულებრივი 2 განზომ მასივი
            // List<KeyValuePair<int, int>> cont = new List<KeyValuePair<int, int>>();
            List<double[]> cont = new List<double[]>();
            for(int i = 0; i < n; i++)
            {
                temp = Console.ReadLine().Split().Select(Double.Parse).ToArray();
                double centre = temp[0], len = temp[1];
                //cont[i, 0] = centre - len / 2;
                //cont[i, 1] = centre + len / 2;

                cont.Add(new double[] { centre - len / 2, centre + len / 2 });
                //double[] myarray = new double[] { centre - len / 2, centre + len / 2 };
                //cont.Add(myarray);
            }

            cont=cont.OrderBy(item => item[0]).ToList();
            // cont = cont.OrderBy(item => item[0]);
            //int[,] tt = new int[,] { { 1, 2 }, { 3, 4 } };
            //int[] tt = new int[] { 1,2 };
           // Array.Sort(cont, new Comparison<double[]>((i1, i2) =>  Convert.ToInt32(i2[0] - i1[0]) ));

            for(int i = 0; i < n - 1; i++)
            {
                // double gap = cont[i + 1, 0] - cont[i, 1];
                double gap = cont[i + 1][0] - cont[i][1];
                if (gap > t) ans += 2;
                else if (gap == t) ans++;
            }
            Console.WriteLine(ans);
        }

    }
}

A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?


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

namespace ProgrammingContest.Codeforces.Round65
{
    class C
    {
        public static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            var xs = Array.ConvertAll(Console.ReadLine().Split(' '), sss=>int.Parse(sss)==1);
            for (int i = 3; i <= n; i++)
            {
                if(n%i != 0)
                    continue;
                int d = n/i;
                for (int j = 0; j <= d; j++)
                {
                    bool ok = true;
                    for (int k = j; ok && k < n; k += d)
                        ok &= xs[k];
                    if (ok)
                    {
                        Console.WriteLine("YES");
                        return;
                    }
                }
            }
            Console.WriteLine("NO");
        }
    }
}

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

namespace code_31
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] arr = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            for (int i = 0; i < n; i++)
            {
                if (arr[i] == 1)
                {
                    int k = i;
                    int step = 0;
                    bool b = false;
                    while (step<=(n-3)/3)
                    {
                        b = false;
                        k = i;
                        step++;
                        k += step;
                        if (k >= n) k = k - n;
                        while (k!=i)
                        {
                            if (arr[k] == 0) { b = true; break; }
                            k += step;
                            if (k >= n) k = k - n;
                        }
                        if (!b)
                        {
                            Console.WriteLine("YES");
                            return;
                        }

                    }
                }

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

There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.


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

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

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

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

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

    class MainClass
    {
        static Tokenizer t;
        static TextWriter w;

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

        public static void Main(string[] args)
        {
            Init();
            int n = t.NextInt();
            List<int> numbers = new List<int>();
            List<int> candidate = new List<int>();
            List<int> ans = new List<int>();
            candidate.Add(0);

            bool hasZero = false;
            for (int i = 0; i < n; i++)
            {
                numbers.Add(t.NextInt());
                if (numbers [i] == 0)
                    hasZero = true;
                if (numbers [i] % 3 == 0)
                    ans.Add(numbers [i]);
                else
                    candidate.Add(numbers [i]);
            }
            if (!hasZero)
            {
                w.WriteLine(-1);
                w.Close();
                return;
            }
            candidate.Sort();

            int c = candidate.Count;
            int[,] dp = new int[c, 3];
            int[,] prev = new int[c, 3];

            prev [0, 0] = 0;
            prev [0, 1] = prev [0, 2] = -1;

            for (int i = 1; i < c; i++)
            {
                int num = candidate [i];
                int curRem = num % 3;
                for (int target = 0; target < 3; target++)
                {
                    int reqRem = (target + 3 - curRem) % 3;
                    if (prev [i - 1, reqRem] >= 0 &&
                        1 + dp [i - 1, reqRem] >= dp [i - 1, target])
                    {
                        dp [i, target] = 1 + dp [i - 1, reqRem];
                        prev [i, target] = i;
                    } else
                    {
                        dp [i, target] = dp [i - 1, target];
                        prev [i, target] = prev [i - 1, target];
                    }
                }
            }

            int rem = 0;
            int cur = prev [c - 1, rem];
            while (cur > 0)
            {
                ans.Add(candidate [cur]);
                rem = (rem + 3 - (candidate [cur] % 3)) % 3;
                cur = prev [cur - 1, rem];
            }

            ans.Sort();
            ans.Reverse();

            if (ans.Count == 0)
            {
                w.WriteLine(-1);
                w.Close();
                return;
            }

            bool allZeros = true;
            for (int i = 0; i < ans.Count; i++)
                if (ans [i] != 0)
                    allZeros = false;

            if (allZeros)
            {
                w.WriteLine(0);
                w.Close();
                return;
            }

            for (int i = 0; i < ans.Count; i++)
            {
                w.Write(ans [i]);
            }
            w.WriteLine();
            w.Close();
        }

    }
}

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

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

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

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

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

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

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

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

                list.Remove(i);

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

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

                list.Add(i);
            }

            Console.WriteLine("-1");
        }

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

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

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


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

class Program
{

    void solve()
    {
        int n=nextInt();
        int at = 0;
        for (int step = 1; step <= n - 1; step++)
        {
            at = (at + step) % n;
            if (step == n - 1)
                Console.WriteLine((at + 1));
            else
                Console.Write((at + 1) + " ");
        }

    }

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

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

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

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

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

using System;
using System.Text;

namespace CodeForce
{
    public class Program
    {
        static void Main(string[] args)
        {
            string input1 = Console.ReadLine();
            var answer = Solve(input1);
            Console.WriteLine(answer);
        }

        public static string Solve(string s)
        {
            var n = int.Parse(s);
            var throws = n - 1;
            var pass = 1;
            var kid = 1;
            var result = new StringBuilder();
            while (throws > 0)
            {
                var targetPos = kid + pass;
                if (targetPos <= n)
                {
                    kid = targetPos;
                }
                else
                {
                    kid = targetPos - n;
                }
                throws--;
                pass++;
                result.Append($"{kid} ");
            }

            result.Remove(result.Length - 1, 1);
            return result.ToString();
        }
    }
}

A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n=5, then after the third throw the child number 2 has the ball again. Overall, n-1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.


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

class Solver
{
    //  test
    static CodeforcesUtils CF = new CodeforcesUtils( new[]{

@"
3
1875
1936
1721
"
,
@"
4
9999
2000
3000
3011
"
,
@"
3
1999
5055
2000
"
});

    public void Solve()
    {
        List<int> ys = new List<int>();
        {
            int n = int.Parse(CF.ReadLine());
            for(int i=0;i<n;i++)
            {
                ys.Add(int.Parse(CF.ReadLine()));
            }
        }

        List<int> zs = new List<int>();
        int prev = 0;
        foreach (var y in ys)
        {
            int? z = _m(y,prev);
            if (z == null)
                break;
            zs.Add(z.Value);
            prev = z.Value;
        }

        if (zs.Count == ys.Count)
        {
            foreach (var z in zs)
                CF.WriteLine(z);
        }
        else
        {
            CF.WriteLine("No solution");
        }
    }

    int? _m(int y, int min)
    {
        int? res = null;

        for (int d = 1; d <= 1000; d*=10)
        {
            int r = y % (d*10);
            r /= d;
            r = y - r * d;

            for (int i = 0; i <= 9; i++)
            {
                int tmp = r + i * d;
                if (tmp < 1000)
                    continue;
                if (tmp > 2011)
                    break;
                if (tmp >= min)
                {
                    if (res == null || tmp < res)
                        res = tmp;
                    break;
                }
            }
        }
        return res;
    }

    Dictionary<int, int> _b_x = new Dictionary<int, int>();
    Dictionary<int, int> _b_y = new Dictionary<int, int>();

    int _init()
    {
        int f = 0;

        string[] ss = new string[5];
        for (int i = 0; i < 5; i++)
            ss[i] = CF.ReadLine();

        for (int i = 0; i < _b_x.Count; i++)
        {
            if (ss[_b_y[i]][_b_x[i]] == 'O')
                f |= (1 << i);
        }

        return f;
    }

    bool _win(int f)
    {
        if (f == 0)
            return false;

        int[] ms = _movable(f);
        bool b = false;
        foreach(int m in ms)
        {
            if (!_win(f))
            {
                b = true;
                break;
            }
        }

        return b;
    }

    int[] _movable(int f)
    {
        return new int[0];
    }

    #region test

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

#if DEBUG
        for (int t=0;t<CF.TestCount;t++ )
        {
            CF.Test(t);
            new Solver().Solve();
        }
#else
        new Solver().Solve();
#endif
        CF.Close();
    }

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

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

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

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

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

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

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

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

        string[] _test_input;

        List<string> _lines;

#if DEBUG
        public 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
}

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

namespace pro
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] p10 = new int[5];
            p10[0] = 1;
            for (int i = 1; i < 5; i++) p10[i] = p10[i - 1] * 10;
            int n = int.Parse(Console.ReadLine());
            int[] dp = new int[n+1];
            dp[0] = 1000;
            for (int i = 0; i < n; i++)
            {
                int x = int.Parse(Console.ReadLine());
                dp[i+1] = 123123;
                for (int j = 0; j < 4; j++)
                {
                    int tx = x / p10[j] % 10;
                    for (int k = 0; k < 10; k++)
                    {
                        int cur = x + (k - tx) * p10[j];
                        if (cur >= dp[i] && dp[i + 1] > cur) dp[i + 1] = cur;
                    }
                }
            }
            if (dp[n] > 2011) Console.WriteLine("No solution");
            else
            {
                for (int i = 1; i <= n; i++) Console.WriteLine(dp[i]);
            }
        }
    }
}

The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.


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

class CS
{
    static List<int> lst;
    static int n, k;

    static bool Check(int t)
    {
        int last = 0;
        int remain = k - 1;
        for (int i = 1; i < lst.Count; i++)
        {
            if (lst[i] - last > t + 1) return false;
            if (i == lst.Count - 1 || lst[i + 1] - last > t + 1)
            {
                last = lst[i];
                if (remain-- == 0)
                {
                    return false;
                }
            }
        }
        return true;
    }

    static void Main(string[] args)
    {
        var line = Console.ReadLine().Split();
        n = int.Parse(line[0]);
        k = int.Parse(line[1]);
        var dat = Console.ReadLine().Trim();

        lst = new List<int>();
        for (int i = 0; i < dat.Length; i++)
        {
            if (dat[i] == '0') lst.Add(i);
        }

        int lo = 0, hi = n, ans = n + 1;
        while (lo <= hi)
        {
            int mid = (lo + hi) / 2;
            if (Check(mid))
            {
                ans = mid;
                hi = mid - 1;
            }
            else lo = mid + 1;
        }
        Console.WriteLine(ans);
    }
}

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string s;
        var nn = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
        var k = nn[1];
        var n = nn[0];
        s = Console.ReadLine();
        int l = -1;
        int r = n;
        while (r - l > 1) {
          int mid = (r + l) / 2;
          int cur = 0;
          int used = 0;
          while (cur < n) {
            if (cur + mid + 1 >= n - 1) {
              break;
            }
            int now = cur + mid + 1;
            while (now >= cur && s[now] == '1') {
              --now;
            }
            if (now == cur) {
              used = k;
              break;
            }
            cur = now;
            used++;
          }
          if (used <= k - 2) {
            r = mid;
          } else {
            l = mid;
          }
        }
        Console.WriteLine(r);
    }

}

Polycarp's workday lasts exactly $$$n$$$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $$$k$$$ bars at the beginning of the workday.In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $$$k$$$ is strictly greater than $$$1$$$.Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.Consider that Polycarp eats a bar in the minute $$$x$$$ and the next bar in the minute $$$y$$$ ($$$x < y$$$). Then the break time is equal to $$$y - x - 1$$$ minutes. It is not necessary for Polycarp to eat all bars he has.


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

public class CasketOfStar
{

public static void Main(string[] args)
    {
        int [] arr = Console.ReadLine().Split().Select(s=>int.Parse(s)).ToArray();
        int n = arr[0];
        int m = arr[1];
        string [] str = new string[n];
        for (int i = 0; i < n; i++) {
            str[i] = Console.ReadLine ();
        }
        long ans = 1;
        for (int i = 0; i < m; i++) {
            Dictionary<char, bool> d = new Dictionary<char, bool>();
            for (int j = 0; j < n; j++) {
                if(!d.ContainsKey(str[j][i]))
                {
                    d[str[j][i]] = true;
                }

            }
            ans = (ans * d.Count()) % 1000000007;
        }
        Console.WriteLine (ans);
    }

}

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

//long a = long.Parse(Console.In.ReadLine());
//int a = int.Parse(Console.In.ReadLine());

//string[] ss = Console.In.ReadLine().Split(new char[] { ' ' });
//long l = long.Parse(ss[0]);
//int l = int.Parse(ss[0]);

class c108_p3
{
    static void Main()
    {
        new c108_p3().myMain();
    }

    void myMain()
    {
        //Console.SetIn(new StreamReader(new FileStream("../../in.txt", FileMode.Open)));
        //StreamWriter out_sw = new StreamWriter(new FileStream("../../out.txt", FileMode.Create));
        //Console.SetOut(out_sw);

        string[] ss = Console.In.ReadLine().Split(new char[] { ' ' });
        int n = int.Parse(ss[0]);
        int m = int.Parse(ss[1]);
        string[] names = new string[n];
        for (int i = 0; i < n; i++)
            names[i] = Console.In.ReadLine();
        long number = 1;
        for (int k = 0; k < m; k++)
        {
            char[] chs = new char[n];
            for (int i = 0; i < n; i++)
                chs[i] = names[i][k];
            number = (number * chs.Distinct().Count()) % 1000000007;
        }

        Console.Out.WriteLine(number);
        //out_sw.Close();
    }
}

One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1≤i<j≤n, 1≤k≤m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (10^9+7).

[{'input': '2 3\nAAB\nBAA\n', 'output': ['4\n']}, {'input': '4 5\nABABA\nBCGDG\nAAAAA\nYABSA\n', 'output': ['216\n']}, {'input': '1 1\nE\n', 'output': ['1\n']}, {'input': '2 2\nNS\nPD\n', 'output': ['4\n']}, {'input': '3 4\nPJKD\nNFJX\nFGFK\n', 'output': ['81\n']}, {'input': '4 5\nSXFMY\nATHLM\nKDDQW\nZWGDS\n', 'output': ['1024\n']}, {'input': '20 14\nJNFKBBBJYZHWQE\nLBOKZCPFNKDBJY\nXKNWGHQHIOXUPF\nDDNRUKVUGHWMXW\nMTIZFNAAFEAPHX\nIXBQOOHEULZYHU\nMRCSREUEOOMUUN\nHJTSQWKUFYZDQU\nGMCMUZCOPRVEIQ\nXBKKGGJECOBLTH\nXXHTLXCNJZJUAF\nVLJRKXXXWMTPKZ\nPTYMNPTBBCWKAD\nQYJGOBUBHMEDYE\nGTKUUVVNKAHTUI\nZNKXYZPCYLBZFP\nQCBLJTRMBDWNNE\nTDOKJOBKEOVNLZ\nFKZUITYAFJOQIM\nUWQNSGLXEEIRWF\n', 'output': ['515139391\n']}, {'input': '5 14\nAQRXUQQNSKZPGC\nDTTKSPFGGVCLPT\nVLZQWWESCHDTAZ\nCOKOWDWDRUOMHP\nXDTRBIZTTCIDGS\n', 'output': ['124999979\n']}, {'input': '9 23\nOILBYKHRGMPENVFNHLSIUOW\nLPJFHTUQUINAALRDGLSQUXR\nLYYJJEBNZATAFQWTDZSPUNZ\nHSJPIQKKWWERJZIEMLCZUKI\nOJYIEYDGPFWRHCMISJCCUEM\nLMGKZVFYIVDRTIHBWPCNUTG\nUBGGNCITVHAIPKXCLTSAULQ\nOWSAWUOXQDBSXXBHTLSXUVD\nUGQTIZQPBGMASRQPVPSFUWK\n', 'output': ['454717784\n']}, {'input': '25 4\nLVKG\nMICU\nZHKW\nLFGG\nOWQO\nLCQG\nLVXU\nOUKB\nLNQX\nZJTO\nOOQX\nLVQP\nMFQB\nMRQV\nOIQH\nOPXX\nXFKU\nFCQB\nZPKH\nLVCH\nNFCU\nOVQW\nOZKU\nLFHX\nLPXO\n', 'output': ['5733\n']}, {'input': '30 10\nUTNTGOKZYJ\nQHOUHNYZVW\nLTVGHJRZVW\nMZHYHOLZYJ\nERYEUEPZYE\nUZDBFTURYJ\nRVSMQTIZGW\nWDJQHMIRYY\nKCORHQPZYE\nRRPLFOZZVY\nJTXMFNNNYJ\nMVTGGOZZVV\nEHAFFNUZVF\nLBRNWJZNYE\nJVMOHTPZYJ\nWTARFJLZVV\nLVJCWOURVW\nLCLQFJYRVV\nQVBVGNJRYF\nNTZGHOLRYE\nMGQKHOUPYJ\nRRSSBXPZYJ\nRYCRGTLZYJ\nJRDEGNKRVW\nRZKFGHYRVG\nMDJBFNIZYG\nMPLWHXIZYE\nSRZMHMURVE\nMTEBBMRZYJ\nJPJIFOLZYM\n', 'output': ['919913906\n']}, {'input': '40 7\nPNTVVER\nPAHTQDR\nRXMJVAS\nVIQNLYC\nILPUSVX\nYJOXQDJ\nSEFODTO\nOTJMREL\nLIQRZGD\nLBJJPOR\nRUTYHQO\nRIWEPBD\nKQUMFIB\nISTRRYH\nXBTOTGK\nRFQODEY\nHDSTZTP\nYCXFAGL\nAREGRFU\nLELZUYU\nGVABDKH\nFJAMMME\nACVULXE\nJHVPJAS\nAAQNMBX\nJJGUCXG\nOQATILQ\nNEOSHJM\nHFLWOFM\nICYEQHY\nFACGLYP\nPLLXJEQ\nDCHXYPB\nAGDDZJJ\nLSQRXTN\nHDQZXIY\nNAHDDWW\nQCMXRQN\nFDUDSZO\nHKBEVTW\n', 'output': ['206575993\n']}, {'input': '2 2\nAA\nBB\n', 'output': ['4\n']}, {'input': '1 10\nAAAAAAAAAA\n', 'output': ['1\n']}, {'input': '2 8\nAAAAAAAA\nBBBBBBBB\n', 'output': ['256\n']}, {'input': '10 10\nAAAAAAAAAA\nBBBBBBBBBB\nCCCCCCCCCC\nDDDDDDDDDD\nAAAAAAAAAA\nBBBBBBBBBB\nCCCCCCCCCC\nDDDDDDDDDD\nAAAAAAAAAA\nBBBBBBBBBB\n', 'output': ['1048576\n']}, {'input': '1 20\nAAAAAAAAAAAAAAAAAAAA\n', 'output': ['1\n']}, {'input': '20 1\nA\nB\nC\nD\nE\nF\nG\nA\nB\nC\nD\nE\nF\nG\nA\nB\nC\nD\nE\nF\n', 'output': ['7\n']}, {'input': '5 60\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\nCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\n', 'output': ['449874206\n']}, {'input': '50 4\nAAAA\nBBBB\nCCCC\nDDDD\nEEEE\nFFFF\nGGGG\nHHHH\nIIII\nJJJJ\nAAAA\nBBBB\nCCCC\nDDDD\nEEEE\nFFFF\nGGGG\nHHHH\nIIII\nJJJJ\nAAAA\nBBBB\nCCCC\nDDDD\nEEEE\nFFFF\nGGGG\nHHHH\nIIII\nJJJJ\nAAAA\nBBBB\nCCCC\nDDDD\nEEEE\nFFFF\nGGGG\nHHHH\nIIII\nJJJJ\nAAAA\nBBBB\nCCCC\nDDDD\nEEEE\nFFFF\nGGGG\nHHHH\nIIII\nJJJJ\n', 'output': ['10000\n']}, {'input': '1 100\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n', 'output': ['1\n']}, {'input': '100 1\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\nA\n', 'output': ['1\n']}, {'input': '100 1\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\nA\nB\n', 'output': ['2\n']}, {'input': '100 1\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nA\nB\n', 'output': ['14\n']}, {'input': '100 1\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\nW\nX\nY\nZ\nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM\nN\nO\nP\nQ\nR\nS\nT\nU\nV\n', 'output': ['26\n']}]


using System;
using System.Collections.Generic;

class Program
{
    const long inf = int.MaxValue;
	void solve()
	{

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

        long b = 0;
        long c=0;
        foreach (char ch in s[2])
        {
            c = (10 * c + ch - '0');
        }
        foreach (char ch in s[0])
            b = (10 * b + ch - '0') % c;
        long ret = 1;
        long p = b;
        char[] t = s[1].ToCharArray();
        for (int i = t.Length - 1; i >= 0; i--)
        {
            if (t[i] == '0')
                t[i] = '9';
            else
            {
                t[i]--;
                break;
            }
        }
        for (int i = t.Length - 1; i >= 0; i--)
        {
            long np = 1;
            for (int j = 0; j < t[i] - '0'; j++)
                np = (np * p) % c;
            ret *= np;
            ret %= c;
            for (int j = t[i] - '0'; j <= 9; j++)
                np = (p * np) % c;
            p = np;
        }
        ret = ret * (b - 1 + c) % c;
        if (ret == 0)
            ret = c;
        println(ret);

	}

    ////////////

    private void println(string Stringst)
    {
        Console.WriteLine(Stringst);
    }
    private void println(int Intnum)
    {
        Console.WriteLine(Intnum);
    }
    private void println(long Longnum)
    {
        Console.WriteLine(Longnum);
    }
    private void println(double Doublenum)
    {
        Console.WriteLine(Doublenum);
    }

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

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

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

using System;
using System.Collections.Generic;

class Program
{
    const long inf = int.MaxValue;
	void solve()
	{

        string b = nextString();
        char[]n = nextString().ToCharArray();
        for (int i = n.Length - 1; i >= 0; i--)
        {
            if (n[i] == '0')
                n[i] = '9';
            else
            {
                n[i]--;
                break;
            }
        }
        long mod= nextInt();
        long num = 0;

        foreach (char ch in b)
        {
            num = 10 * num + ch - '0';
            num %= mod;
        }
        Dictionary<long, int> d = get(mod);
        Dictionary<long, long> chinese = new Dictionary<long, long>();
        long r = 1;
        foreach (KeyValuePair<long, int> x in d)
        {
            r *= (long)Math.Pow(x.Key, x.Value - 1) * (x.Key - 1);
        }
        long remOfr = 0;
        foreach (char c in n)
        {
            remOfr = 10 * remOfr + c - '0';
            remOfr %= r;
        }
        foreach(KeyValuePair<long,int>x in d)
        {
            if (num % x.Key == 0)
            {
                if (n.Length > 3)
                    chinese[x.Key] = 0;
                else
                    chinese[x.Key] = modPow(num, getNum(n), (long)Math.Pow(x.Key, x.Value));
            }
            else
            {
                chinese[x.Key] = modPow(num, remOfr, (long)Math.Pow(x.Key, x.Value));
            }
        }
        long ret = 0;
        foreach (KeyValuePair<long, int> x in d)
        {
            long ni = mod / (long)Math.Pow(x.Key, x.Value);
            long phi = (long)Math.Pow(x.Key, x.Value - 1) * (x.Key - 1);
            long inv = getInv(ni, (long)Math.Pow(x.Key, x.Value));
            ret += inv * ni%mod * chinese[x.Key];
            ret %= mod;
        }
        ret = (num - 1 + mod) * ret % mod;
        ret += mod;
        ret %= mod;
        if (ret == 0)
            ret = mod;
        println(ret);
	}

    private long getInv(long a, long b)
    {
        return euclid(a, b)[0];
    }
    long[] euclid(long a, long b)
    {
        if (b == 0)
        {
            return new long[] { 1, 0, a };
        }
        else
        {
            long[] p = euclid(b, a % b);
            long[] ret = new long[3];
            ret[0] = p[1];
            ret[1] = p[0] - a / b * p[1];
            ret[2] = p[2];
            return ret;
        }
    }

    private long modPow(long num, long p, long mod)
    {
        if (p == 0)
            return 1;
        long ret = modPow(num, p / 2, mod);
        ret *= ret;
        ret %= mod;
        if (p % 2 == 1)
            ret *= num;
        ret %= mod;
        return ret;
    }

    private long getNum(char[]n)
    {
        long ret = 0;
        foreach (char ch in n)
            ret = 10 * ret + ch - '0';
        return ret;

    }

    private Dictionary<long, int> get(long n)
    {
        Dictionary<long, int> ret = new Dictionary<long, int>();
        for(long i=2;i*i<=n;i++)
            if (n % i == 0)
            {
                int cnt = 0;
                while (n % i == 0)
                {
                    cnt++;
                    n /= i;
                }
                ret[i] = cnt;
            }
        if (n > 1)
        {
            ret[n] = 1;
        }
        return ret;
    }

    ////////////

    private void println(string Stringst)
    {
        Console.WriteLine(Stringst);
    }
    private void println(int Intnum)
    {
        Console.WriteLine(Intnum);
    }
    private void println(long Longnum)
    {
        Console.WriteLine(Longnum);
    }
    private void println(double Doublenum)
    {
        Console.WriteLine(Doublenum);
    }

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

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

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

Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.


using System;
using System.Collections.Generic;

namespace yandex2011_qual_1_average_score {
    internal class Program {
        private static void Main(string[] args) {
            int n = int.Parse(Console.ReadLine());
            string s = Console.ReadLine();
            string[] ss = s.Split(' ');
            int a = int.Parse(ss[0]);
            int b = int.Parse(ss[1]);
            s = Console.ReadLine();
            ss = s.Split(' ');
            ScorePair[] scores = new ScorePair[n];
            for (int i = 0; i < n; i++) {
                int score = int.Parse(ss[i]);
                scores[i] = new ScorePair(score, i);
            }
            int[] result = new int[n];
            if (a == b) {
                for (int i = 0; i < a; i++) {
                    result[scores[i].Index] = 1;
                }
                for (int i = 0; i < b; i++) {
                    result[scores[i + a].Index] = 2;
                }
            } else if (a < b) {
                Array.Sort(scores, new MyComparer2());
                for (int i = 0; i < b; i++) {
                    result[scores[i].Index] = 2;
                }
                for (int i = 0; i < a; i++) {
                    result[scores[i + b].Index] = 1;
                }
            } else {
                Array.Sort(scores, new MyComparer());
                for (int i = 0; i < a; i++) {
                    result[scores[i].Index] = 1;
                }
                for (int i = 0; i < b; i++) {
                    result[scores[i + a].Index] = 2;
                }
            }
            for (int i = 0; i < n; i++) {
                Console.Write(result[i] + " ");
            }
        }

        #region Nested type: MyComparer

        internal class MyComparer : IComparer<ScorePair> {
            #region IComparer<ScorePair> Members

            public int Compare(ScorePair x, ScorePair y) {
                if (x.Score < y.Score) {
                    return -1;
                }
                if (x.Score > y.Score) {
                    return 1;
                }
                return x.Index.CompareTo(y.Index);
            }

            #endregion
        }

        #endregion

        #region Nested type: MyComparer2

        internal class MyComparer2 : IComparer<ScorePair> {
            #region IComparer<ScorePair> Members

            public int Compare(ScorePair x, ScorePair y) {
                if (x.Score < y.Score) {
                    return -1;
                }
                if (x.Score > y.Score) {
                    return 1;
                }
                return -x.Index.CompareTo(y.Index);
            }

            #endregion
        }

        #endregion

        #region Nested type: ScorePair

        internal struct ScorePair {
            public int Index;

            public int Score;

            public ScorePair(int score, int index) {
                Score = score;
                Index = index;
            }
        }

        #endregion
    }
}

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

namespace ProgrammingContest.Codeforces.Yandex_Open_2011.Qualification_1
{
    class C
    {
        public static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            var xs = Array.ConvertAll(Console.ReadLine().Split(' '), sss => int.Parse(sss));
            var ys = Array.ConvertAll(Console.ReadLine().Split(' '), sss => int.Parse(sss));
            var yss = (int[])ys.Clone();
            int a = xs[0],
                b = xs[1];

            if (n == 2 * a)
            {
                for (int i = 0; i < a; i++)
                    Console.Write("1 ");
                for (int i = 0; i < b; i++)
                    Console.Write("2 ");
                return;
            }
            int[] fetch = new int[5];
            QuickSort(yss);
            if (n > 2 * a)
            {
                Array.Reverse(yss);
                for (int i = 0; i < a; i++)
                    fetch[yss[i] - 1]++;
                for (int i = 0; i < n; i++)
                    if (fetch[ys[i] - 1] > 0)
                    {
                        fetch[ys[i] - 1]--;
                        Console.Write("1 ");
                    }
                    else
                    {
                        Console.Write("2 ");
                    }
            }
            else
            {
                for (int i = 0; i < a; i++)
                    fetch[yss[i] - 1]++;
                for (int i = 0; i < n; i++)
                    if (fetch[ys[i] - 1] > 0)
                    {
                        fetch[ys[i] - 1]--;
                        Console.Write("1 ");
                    }
                    else
                    {
                        Console.Write("2 ");
                    }
            }
        }

        #region QuickSort
        static void Swap(int[] xs, int i, int j) { int t = xs[i]; xs[i] = xs[j]; xs[j] = t; }
        static int[] QuickSort(int[] xs) { return QuickSort(xs, 0, xs.Length); }
        static int[] QuickSort(int[] xs, int start, int count)
        {
            if (count < 2) return xs;

            Stack<int> s = new Stack<int>(),
                       c = new Stack<int>();

            s.Push(start);
            c.Push(count);

            while (s.Count > 0)
            {
                start = s.Pop();
                count = c.Pop();

                int last = start + count - 1,
                    forward = start - 1,
                    backward = start + count,
                    pivot = xs[start + count / 2];

                while (true)
                {
                    while (xs[++forward] < pivot) ;
                    while (pivot < xs[--backward]) ;
                    if (forward >= backward) break;
                    Swap(xs, forward, backward);
                }

                if (start < forward - 1)
                {
                    s.Push(start);
                    c.Push(forward - start);
                    //QuickSort(xs, start, forward - start);
                }

                if (backward + 1 < last)
                {
                    s.Push(backward + 1);
                    c.Push(last - (backward + 1) + 1);
                    //QuickSort(xs, backward + 1, last - (backward + 1) + 1);
                }
            }

            return xs;
        }
        #endregion
    }
}

After the educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received n marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark.Now it's time to show the journal to his strict parents. Polycarp knows that recently at the Parent Meeting the parents were told that he received a Safety Studies marks and b PE marks (a+b=n). Now Polycarp wants to write a subject's name in front of each mark so that:   there are exactly a Safety Studies marks,  there are exactly b PE marks,  the total average score in both subjects is maximum. An average subject grade is the sum of all marks in it, divided by the number of them. Of course, the division is performed in real numbers without rounding up or down. Polycarp aims to maximize the x1+x2, where x1 is the average score in the first subject (Safety Studies), and x2 is the average score in the second one (Physical Education).


using System;
using System.Linq;

namespace CSharp
{
    class _137B
    {
        public static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            Console.WriteLine(Console.ReadLine().Split().GroupBy(token => int.Parse(token)).Sum(x => x.Key > n ? x.Count() : x.Count() - 1));
        }
    }
}

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

namespace ProblemB
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            string[] token = Console.ReadLine().Split();
            int[] a = new int[n+1];
            int tmp;
            for (int i = 0; i < n; i++)
            {
                tmp = int.Parse(token[i]);
                a[tmp>n?n:tmp- 1]++;
            }
            int result = 0;
            for (int i=0; i<n; i++)
                if (a[i]==0) result++;
            Console.WriteLine(result);

        }
    }
}

"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1,a2,...,an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).


using System;
using System.Linq;

namespace CSharp
{
    class _215A
    {
        public static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            var a = Console.ReadLine().Split().Select(token => int.Parse(token)).ToArray();

            int m = int.Parse(Console.ReadLine());
            var b = Console.ReadLine().Split().Select(token => int.Parse(token)).ToArray();

            Console.WriteLine(Enumerable.Range(0, n).SelectMany(i => Enumerable.Range(0, m).Where(j => b[j] % a[i] == 0).Select(j => b[j] / a[i])).GroupBy(x => x).OrderByDescending(x => x.Key).First().Count());
        }
    }
}

using System;
using System.Linq;
namespace codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            int n= int.Parse(Console.ReadLine());
            int[] a= Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
            int m = int.Parse(Console.ReadLine());
            int[] b= Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
            int count = 0;
            int max = 0;
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < m; j++)
                {
                    if (b[j]%a[i]==0)
                    {
                        int rez = b[j] / a[i];
                        if (rez>max)
                        {
                            max = rez;
                            count=1;
                        }
                        else if (rez==max)
                        {
                            count++;
                        }
                    }
                }
            }
            Console.WriteLine(count) ;
        }
    }
}

Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0<a1<a2<...<an) teeth, and the j-th star on the rear wheel axle has bj (0<b1<b2<...<bm) teeth. Any pair (i,j) (1≤i≤n; 1≤j≤m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i,j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i,j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i,j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.


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

namespace SharpTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string have = Console.ReadLine();
            string need = Console.ReadLine();
            int[] cnt = new int[256];
            for (int i = 0; i < have.Length; i++)
            {
                if (Char.IsLetter(have[i])) cnt[have[i]]++;
            }
            for (int i = 0; i < need.Length; i++)
            {
                if (Char.IsLetter(need[i])) cnt[need[i]]--;
            }
            bool res = true;
            foreach (var x in cnt)
            {
                if (x < 0)
                    res = false;
            }
            Console.WriteLine(res?"YES":"NO");
        }
    }
}

using System;
using System.Collections.Generic;

namespace _43B
{
    class Program
    {
        static void Main(string[] args)
        {
            //var dict = new Dictionary<char, int>();
            //string ans = "YES";
            //foreach (char item in Console.ReadLine())
            //{
            //    if (item == ' ') continue;
            //    if (dict.ContainsKey(item))
            //        dict[item]++;
            //    else dict.Add(item, 1);
            //}
            //foreach (char item in Console.ReadLine())
            //{
            //    if (item == ' ') continue;
            //    if (dict.ContainsKey(item) && dict[item] > 0)
            //        dict[item]--;
            //    else
            //    {
            //        ans = "NO";
            //        break;
            //            }
            //}
            //Console.WriteLine(ans);
            string ans = "YES";
            string mainStr = Console.ReadLine();
            foreach (char item in Console.ReadLine())
            {
                if (item == ' ') continue;
                int index = mainStr.IndexOf(item);
                if (index != -1)
                    mainStr = mainStr.Remove(index, 1);
                else
                {
                    ans = "NO";
                    break;
                }
            }
            Console.WriteLine(ans);
        }
    }
}

Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

[{'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\nwhere is your dog\n', 'output': ['NO\n']}, {'input': 'Instead of dogging Your footsteps it disappears but you dont notice anything\nYour dog is upstears\n', 'output': ['YES\n']}, {'input': 'Instead of dogging your footsteps it disappears but you dont notice anything\nYour dog is upstears\n', 'output': ['NO\n']}, {'input': 'abcdefg hijk\nk j i h g f e d c b a\n', 'output': ['YES\n']}, {'input': 'HpOKgo\neAtAVB\n', 'output': ['NO\n']}, {'input': 'GRZGc\nLPzD\n', 'output': ['NO\n']}, {'input': 'GtPXu\nd\n', 'output': ['NO\n']}, {'input': 'FVF\nr \n', 'output': ['NO\n']}, {'input': 'HpOKgo\nogK\n', 'output': ['YES\n']}, {'input': 'GRZGc\nZG\n', 'output': ['YES\n']}, {'input': 'HpOKgoueAtAVBdGffvQheJDejNDHhhwyKJisugiRAH OseK yUwqPPNuThUxTfthqIUeb wS jChGOdFDarNrKRT  MlwKecxWNoKEeD BbiHAruE XMlvKYVsJGPP\nAHN  XvoaNwV  AVBKwKjr u      U K wKE D K   Jy KiHsR h d W  Js IHyMPK Br iSqe  E fDA   g H\n', 'output': ['YES\n']}, {'input': 'GRZGcsLPzDrCSXhhNTaibJqVphhjbcPoZhCDUlzAbDnRWjHvxLKtpGiFWiGbfeDxBwCrdJmJGCGv GebAOinUsFrlqKTILOmxrFjSpEoVGoTdSSstJWVgMLKMPettxHASaQZNdOIObcTxtF qTHWBdNIKwj\nWqrxze Ji x q aT GllLrRV jMpGiMDTwwS JDsPGpAZKACmsFCOS CD Sj  bCDgKF  jJxa RddtLFAi VGLHH SecObzG q  hPF \n', 'output': ['YES\n']}, {'input': 'GtPXuwdAxNhODQbjRslDDKciOALJrCifTjDQurQEBeFUUSZWwCZQPdYwZkYbrduMijFjgodAOrKIuUKwSXageZuOWMIhAMexyLRzFuzuXqBDTEaWMzVdbzhxDGSJC SsIYuYILwpiwwcObEHWpFvHeBkWYNitqYrxqgHReHcKnHbtjcWZuaxPBVPb\nTQIKyqFaewOkY lZUOOuxEw EwuKcArxRQGFYkvVWIAe SuanPeHuDjquurJu aSxwgOSw jYMwjxItNUUArQjO BIujAhSwttLWp\n', 'output': ['YES\n']}, {'input': 'FVFSr unvtXbpKWF vPaAgNaoTqklzVqiGYcUcBIcattzBrRuNSnKUtmdGKbjcE\nUzrU K  an GFGR        Wc zt iBa     P c    T K v p     V In   b           B   c\n', 'output': ['YES\n']}, {'input': 'lSwjnYLYtDNIZjxHiTawdh ntSzggZogcIZTuiTMWVgwyloMtEhqkrOxgIcFvwvsboXUPILPIymFAEXnhApewJXJNtFyZ\nAoxe  jWZ u  yImg  o AZ FNI w lpj  tNhT g y  ZYcb rc J    w Dlv\n', 'output': ['YES\n']}, {'input': 'kvlekcdJqODUKdsJlXkRaileTmdGwUHWWgvgUokQxRzzbpFnswvNKiDnjfOFGvFcnaaiRnBGQmqoPxDHepgYasLhzjDgmvaFfVNEcSPVQCJKAbSyTGpXsAjIHr\nGjzUllNaGGKXUdYmDFpqFAKIwvTpjmqnyswWRTnxlBnavAGvavxJemrjvRJc\n', 'output': ['YES\n']}, {'input': 'kWbvhgvvoYOhwXmgTwOSCDXrtFHhqwvMlCvsuuAUXMmWaYXiqHplFZZemhgkTuvsUtIaUxtyYauBIpjdbyYxjZ ZkaBPzwqPfqF kCqGRmXvWuabnQognnkvdNDtRUsSUvSzgBuxCMBWJifbxWegsknp\nBsH   bWHJD n Ca T xq  PRCv  tatn Wjy sm  I q s WCjFqdWe  t W XUs  Do  eb Pfh ii  hTbF  O Fll\n', 'output': ['YES\n']}, {'input': 'OTmLdkMhmDEOMQMiW ZpzEIjyElHFrNCfFQDp SZyoZaEIUIpyCHfwOUqiSkKtFHggrTBGkqfOxkChPztmPrsHoxVwAdrxbZLKxPXHlMnrkgMgiaHFopiFFiUEtKwCjpJtwdwkbJCgA bxeDIscFdmHQJLAMNhWlrZisQrHQpvbALWTwpf jnx\nDbZwrQbydCdkJMCrftiwtPFfpMiwwrfIrKidEChKECxQUBVUEfFirbGWiLkFQkdJiFtkrtkbIAEXCEDkwLpK\n', 'output': ['YES\n']}, {'input': 'NwcGaIeSkOva\naIa\n', 'output': ['YES\n']}, {'input': 'gSrAcVYgAdbdayzbKGhIzLDjyznLRIJH KyvilAaEddmgkBPCNzpmPNeGEbmmpAyHvUSoPvnaORrPUuafpReEGoDOQsAYnUHYfBqhdcopQfxJuGXgKnbdVMQNhJYkyjiJDKlShqBTtnnDQQzEijOMcYRGMgPGVhfIReYennKBLwDTVvcHMIHMgVpJkvzTrezxqS\nHJerIVvRyfrPgAQMTI AqGNO mQDfDwQHKgeeYmuRmozKHILvehMPOJNMRtPTAfvKvsoGKi xHEeKqDAYmQJPUXRJbIbHrgVOMGMTdvYiLui\n', 'output': ['YES\n']}, {'input': 'ReB hksbHqQXxUgpvoNK bFqmNVCEiOyKdKcAJQRkpeohpfuqZabvrLfmpZOMcfyFBJGZwVMxiUPP pbZZtJjxhEwvrAba\nJTCpQnIViIGIdQtLnmkVzmcbBZR CoxAdTtWSYpbOglDFifqIVQ vfGKGtLpxpJHiHSWCMeRcrVOXBGBhoEnVhNTPWGTOErNtSvokcGdgZXbgTEtISUyTwaXUEIlJMmutsdCbiyrPZPJyRdOjnSuAGttLy\n', 'output': ['NO\n']}, {'input': 'hrLzRegCuDGxTrhDgVvM KowwyYuXGzIpcXdSMgeQVfVOtJZdkhNYSegwFWWoPqcZoeapbQnyCtojgkcyezUNHGGIZrhzsKrvvcrtokIdcnqXXkCNKjrOjrnEAKBNxyDdiMVeyLvXxUYMZQRFdlcdlcxzKTeYzBlmpNiwWbNAAhWkMoGpRxkCuyqkzXdKWwGH\nJESKDOfnFdxPvUOCkrgSBEPQHJtJHzuNGstRbTCcchRWJvCcveSEAtwtOmZZiW\n', 'output': ['NO\n']}, {'input': 'yDBxCtUygQwWqONxQCcuAvVCkMGlqgC zvkfEkwqbhMCQxnkwQIUhucCbVUyOBUcXvTNEGriTBwMDMfdsPZgWRgIUDqM\neptVnORTTyixxmWIBpSTEwOXqGZllBgSxPenYCDlFwckJlWsoVwWLAIbPOmFqcKcTcoQqahetl KLfVSyaLVebzsGwPSVbtQAeUdZAaJtfxlCEvvaRhLlVvRJhKat IaB awdqcDlrrhTbRxjEbzGwcdmdavkhcjHjzmwbxAgw\n', 'output': ['NO\n']}, {'input': 'jlMwnnotSdlQMluKWkJwAeCetcqbIEnKeNyLWoKCGONDRBQOjbkGpUvDlmSFUJ bWhohqmmIUWTlDsvelUArAcZJBipMDwUvRfBsYzMdQnPDPAuBaeJmAxVKwUMJrwMDxNtlrtAowVWqWiwFGtmquZAcrpFsLHCrvMSMMlvQUqypAihQWrFMNoaqfs IBg\nNzeWQ bafrmDsYlpNHSGTBBgPl WIcuNhyNaNOEFvL\n', 'output': ['NO\n']}, {'input': 'zyWvXBcUZqGqjHwZHQryBtFliLYnweXAoMKNpLaunaOlzaauWmLtywsEvWPiwxJapocAFRMjrqWJXYqfKEbBKnzLO\npsbi bsXpSeJaCkIuPWfSRADXdIClxcDCowwJzGCDTyAl\n', 'output': ['NO\n']}, {'input': 'kKhuIwRPLCwPFfcnsyCfBdnsraGeOCcLTfXuGjqFSGPSAeDZJSS bXKFanNqWjpFnvRpWxHJspvisDlADJBioxXNbVoXeUedoPcNEpUyEeYxdJXhGzFAmpAiHotSVwbZQsuWjIVhVaEGgqbZHIoDpiEmjTtFylCwCkWWzUOoUfOHxEZvDwNpXhBWamHn\nK VpJjGhNbwCRhcfmNGVjewBFpEmPlIKeTuWiukDtEWpjgqciqglkyNfWrBLbGAKvlNWxaUelJmSlSoakSpRzePvJsshOsTYrMPXdxKpaShjyVIXGhRIAdtiGpNwtiRmGTBZhkJqIMdxMHX RMxCMYcWjcjhtCHyFnCvjjezGbkRDRiVxkbh\n', 'output': ['NO\n']}, {'input': 'AXssNpFKyQmJcBdBdfkhhMUzfqJVgcLBddkwtnFSzSRUCjiDcdtmkzIGkCKSxWUEGhmHmciktJyGMkgCductyHx\nI nYhmJfPnvoKUiXYUBIPIcxNYTtvwPUoXERZvY ahlDpQFNMmVZqEBiYqYlHNqcpSCmhFczBlOAhsYFeqMGfqL EJsDNOgwoJfBzqijKOFcYQ\n', 'output': ['NO\n']}, {'input': 'lkhrzDZmkdbjzYKPNMRkiwCFoZsMzBQMnxxdKKVJezSBjnLjPpUYtabcPTIaDJeDEobbWHdKOdVfMQwDXzDDcSrwVenDEYpMqfiOQ xSsqApWnAMoyhQXCKFzHvvzvUvkWwmwZrvZz\nsUzGspYpRFsHRbRgTQuCBgnFgPkisTUfFNwyEEWWRiweWWgjRkVQxgTwxOzdsOwfrGIH O gCXpzvHzfItuEHaihmugEyymSJIogYwX qAwcwIItidfnzZDhZgQHi eRjMAeVkJHceDZuJkmxGowOsmcGYYvk Ajtgi TxwihvjLViNZjvscTWvsaQUelTSivLShhEl\n', 'output': ['NO\n']}, {'input': 'BRsVjyNhrqRHVwrJzuzRigEhdpbDmaACSPfed\nlWqKTjlrqOCUbgBBZdZDGCeQJDXawPnnDkQdZDgwrEQk\n', 'output': ['NO\n']}, {'input': 'KRmINuyBYPwiTsdlyiNVuylToysJKmOpcLovAtwGPqrgFJQNAYvuAiyQRkeFMECVZvkDEmTauXlyjAaYRnTJXORMZRnTakBaUzSelMilejySDIZjQjzcOIrwXdvDvpeRIkoBgreyFXIyyIZutjiEBtwrmzQtPVUhvvdEtDMbXjBpoPVjGdM EXTAK JbCnw\nXZZqlJvzKKtvdNlzFPDTYxidqlsgufVzyEmO FZuLQ vVQsJESNviUCovCK NwwlbxsmPtOJNmAonCqrOZ bZ LVKAsQGmoLnYjeekvEIECFk\n', 'output': ['NO\n']}]