Igor K. very much likes a multiplayer role playing game WineAge II. Who knows, perhaps, that might be the reason for his poor performance at the university. As any person who plays the game, he is interested in equipping his hero with as good weapon and outfit as possible. One day, as he was reading the game's forum yet again, he discovered a very interesting fact. As it turns out, each weapon in the game is characterised with k different numbers: a1, ..., ak. They are called hit indicators and according to the game developers' plan they are pairwise coprime. The damage that is inflicted during a hit depends not only on the weapon's characteristics, but also on the hero's strength parameter. Thus, if the hero's strength equals n, than the inflicted damage will be calculated as the number of numbers on the segment , that aren't divisible by any hit indicator ai.Recently, having fulfilled another quest, Igor K. found a new Lostborn sword. He wants to know how much damage he will inflict upon his enemies if he uses it.

The first line contains two integers: n and k (1 ≤ n ≤ 1013, 1 ≤ k ≤ 100). They are the indicator of Igor K's hero's strength and the number of hit indicators. The next line contains space-separated k integers ai (1 ≤ ai ≤ 1000). They are Lostborn sword's hit indicators. The given k numbers are pairwise coprime.

Print the single number — the damage that will be inflicted by Igor K.'s hero when he uses his new weapon.  Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.

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

class Program
{
    long[] a;
    long[,] dp;
    int maxn = 100000;
    void solve()
    {
        //test();
        long n = nextLong();
        a = new long[nextInt()];
        for (int i = 0; i < a.Length; i++)
            a[i] = nextLong();
        long res = n - doIt(n);
        println(res);

    }
    long doIt(long n)
    {
        Array.Sort(a);
        Array.Reverse(a);
        dp = new long[100, maxn];
        for (int i = 0; i < 100; i++)
            for (int j = 0; j < maxn; j++)
                dp[i, j] = -1;
        return go(n, 0);
    }
    private void test()
    {
        long n = 10000000000000;
        int k = 100;
        a = new long[k];
        int cur = 2;
        for (int i = 0; i < k; i++)
        {
            while (!prime(cur))
                cur++;
            a[i] = cur++;
        }
        println(doIt(n));
    }

    private bool prime(int p)
    {
        for (int i = 2; i * i <= p; i++)
            if (p % i == 0)
                return false;
        return true;
    }

    private long go(long n, int at)
    {
        if (at == a.Length)
            return 0;
        if (n == 0)
            return 0;
        if (n < maxn)
        {
            if (dp[at, n] != -1)
                return dp[at, n];
        }
        long res = go(n, at + 1);
        res += n / a[at];
        res -= go(n / a[at], at + 1);
        if (n < maxn)
        {
            return dp[at, n] = res;
        }
        return res;
    }

    ////////////
    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()
    {
        return int.Parse(nextString());
    }
    long nextLong()
    {
        return long.Parse(nextString());
    }
    double nextDouble()
    {
        return double.Parse(nextString());
    }
    string nextString()
    {
        if (inputInd == inputLine.Length)
            readInput();
        return inputLine[inputInd++];
    }
    static void Main(string[] args)
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        new Program().solve();
    }
}


A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.

The first line contains two space-separated integers n and k (2 ≤ n ≤ 104, 2 ≤ k ≤ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits.

On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one.

NoteIn the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188".The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≤ i ≤ n), that xi < yi, and for any j (1 ≤ j < i) xj = yj. The strings compared in this problem will always have the length n.

using System;
using System.Text;

class Fffuuuu {

    Char[] last;

    Int32 Have(Int32 dig, Int32 delta, Int32[] stat) {
        Int32 have = 0;
        if (dig - delta >= 0) {
            have += stat[dig - delta];
        }
        if (dig + delta < 10) {
            have += stat[dig + delta];
        }
        return have;
    }

    Int32 Pick(String str, Int32 dig, Int32[] stat, Int32 toChange) {
        Int32[] accDist = new Int32[10];
        toChange -= stat[dig];
        for (Int32 pick, dist = 1; toChange > 0; ++dist) {
            if (dig - dist >= 0) {
                pick = Math.Min(toChange, stat[dig - dist]);
                accDist[dist] += pick;
                toChange -= pick;
            }
            if (dig + dist < 10) {
                pick = Math.Min(toChange, stat[dig + dist]);
                accDist[dist] += pick;
                toChange -= pick;
            }
        }

        Int32 score = 0;
        for (Int32 delta, cur, i = 0; i < str.Length; ++i) {
            cur = str[i] & 0xf;
            delta = Math.Abs(cur - dig);
            if (accDist[delta] != 0) {
                if (cur > dig || accDist[delta] == Have(dig, delta, stat)) {
                    score += delta;
                    --accDist[delta];
                    --stat[cur];
                    cur = dig;
                } else {
                    --stat[cur];
                }
            }
            last[i] = (Char) (cur | 0x30);
        }

        return score;
    }

    public Fffuuuu() {
        Int32 toChange = Int32.Parse(Console.ReadLine().Split(' ')[1]);
        String str = Console.ReadLine();
        Int32[] stat = new Int32[10];
        for (Int32 i = 0; i < str.Length; ++stat[str[i++] & 0xf]) { }

        Int32 best = -1;
        String bestString = String.Empty;
        last = new Char[str.Length];
        for (Int32 one, dig = 0; dig < 10; ++dig) {
            one = Pick(str, dig, (Int32[]) stat.Clone(), toChange);
            if (best < 0 || best > one || (best == one && (new String(last).CompareTo(bestString) < 0))) {
                best = one;
                bestString = new String(last);
            }
        }
        Console.WriteLine(best);
        Console.WriteLine(bestString);
    }

    static void Main() {
#if DEBUG
        Console.SetIn(new System.IO.StreamReader("in.txt"));
#endif
        new Fffuuuu();
    }

}


Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains  distinct theorems. Besides, no theorem is mentioned in more than one card (that is,  theorems won't be mentioned in any card). During the exam several students may get the same card.We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 100) — the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 ≤ ai ≤ 100), the i-th number (1 ≤ i ≤ n) corresponds to Vasya's proficiency in the i-th theorem. The third line contains number q (0 ≤ q ≤ 100) — the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card:  integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).

Print two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.

NoteLet's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).The ⌊ x⌋ operation denotes taking integer part of real number x (rounding down).

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

namespace ProgrammingContest.Codeforces.Round90 {
    class B {
        static void Main() {
            Scanner sc = Scanner.FromConsole();
            PrintWriter writer = PrintWriter.ToConsole();

            int n = sc.NextInt(),
                k = sc.NextInt();
            var a = sc.NextInts(n);
            var used = new bool[n];
            int q = sc.NextInt();
            var prevs = new List<int>();
            int uniq = 0;
            for (int i = 0; i < q; i++) {
                var xs = sc.NextInts(n/k);
                prevs.Add(0);
                bool already = false;
                for (int j = 0; j < xs.Length; j++) {
                    already = used[xs[j]-1];
                    used[xs[j] - 1] = true;
                    prevs[i] += a[xs[j]-1];
                }
                if(!already) {
                    uniq++;
                }
            }

            List<int> ys = new List<int>();
            for (int i = 0; i < n; i++)
                if (!used[i])
                    ys.Add(a[i]);
            if (uniq < k) {
                ys.Sort();
                int u=0,v=0;
                for (int i = 0; i < n / k; i++) { u += ys[i]; v += ys[ys.Count - 1 - i]; }
                prevs.Add(u);
                prevs.Add(v);
            }
            prevs.Sort();
            double d = n / k;
            writer.WriteLine("{0:F10} {1:F10}", prevs.First() / d, prevs.Last() / d);
        }

        #region PrintWriter
        class PrintWriter : IDisposable {
            System.IO.TextWriter writer;

            public static PrintWriter ToConsole() {
                return new PrintWriter(Console.Out);
            }

            public static PrintWriter ToFile(string path) {
                return new PrintWriter(new System.IO.StreamWriter(path));
            }

            public void Write(string format, params object[] obj) {
                writer.Write(String.Format(System.Globalization.CultureInfo.InvariantCulture, format, obj));
            }

            public void WriteLine(string format, params object[] obj) {
                writer.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, format, obj));
            }

            private PrintWriter(System.IO.TextWriter w) {
                writer = w;
            }

            public void Dispose() {
                writer.Close();
            }
        }
        #endregion
        #region Scanner
        public class Scanner : IDisposable {
            const int MAX_BUFFER_SIZE = 1024 * 1024 * 16;
            //const string DELIMITER = " \r\n\t";

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

            public enum Option { Buffering, NoBuffering }

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

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

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

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

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

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

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

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

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

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

            public double NextDouble() {
                return double.Parse(NextString(), System.Globalization.CultureInfo.InvariantCulture);
            }

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

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

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

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

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

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

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

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


You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.

The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order. The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order. The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.

Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).

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

namespace Codeforces
{
    public class Input
    {
        private static string _line;

        public static bool Next()
        {
            _line = Console.ReadLine();
            return !string.IsNullOrEmpty(_line);
        }

        public static bool Next(out long a)
        {
            var ok = Next();
            a = ok ? long.Parse(_line) : 0;
            return ok;
        }

        public static bool Next(out long a, out long b)
        {
            var ok = Next();
            if (ok)
            {
                var array = _line.Split(' ').Select(long.Parse).ToArray();
                a = array[0];
                b = array[1];
            }
            else
            {
                a = b = 0;
            }

            return ok;
        }

        public static bool Next(out long a, out long b, out long c)
        {
            var ok = Next();
            if (ok)
            {
                var array = _line.Split(' ').Select(long.Parse).ToArray();
                a = array[0];
                b = array[1];
                c = array[2];
            }
            else
            {
                a = b = c = 0;
            }
            return ok;
        }

        public static bool Next(out long a, out long b, out long c, out long d)
        {
            var ok = Next();
            if (ok)
            {
                var array = _line.Split(' ').Select(long.Parse).ToArray();
                a = array[0];
                b = array[1];
                c = array[2];
                d = array[3];
            }
            else
            {
                a = b = c = d = 0;
            }
            return ok;
        }

        public static bool Next(out long a, out long b, out long c, out long d, out long e)
        {
            var ok = Next();
            if (ok)
            {
                var array = _line.Split(' ').Select(long.Parse).ToArray();
                a = array[0];
                b = array[1];
                c = array[2];
                d = array[3];
                e = array[4];
            }
            else
            {
                a = b = c = d = e = 0;
            }
            return ok;
        }

        public static List<long> Numbers()
        {
            return !Next() ? new List<long>() : _line.Split(' ').Select(long.Parse).ToList();
        }

        public static bool Next(out string value)
        {
            value = string.Empty;
            if (!Next()) return false;
            value = _line;
            return true;
        }
    }

    public class DisjointSet
    {
        private readonly int[] _parent;
        private readonly int[] _rank;
        public int Count { get; private set; }

        public DisjointSet(int count, int initialize = 0)
        {
            Count = count;
            _parent = new int[Count];
            _rank = new int[Count];
            for (var i = 0; i < initialize; i++) _parent[i] = i;
        }

        private DisjointSet(int count, int[] parent, int[] rank)
        {
            Count = count;
            _parent = parent;
            _rank = rank;
        }

        public void Add(int v)
        {
            _parent[v] = v;
            _rank[v] = 0;
        }

        public int Find_Recursive(int v)
        {
            if (_parent[v] == v) return v;
            return _parent[v] = Find(_parent[v]);
        }

        public int Find(int v)
        {
            if (_parent[v] == v) return v;
            var last = v;
            while (_parent[last] != last) last = _parent[last];
            while (_parent[v] != v)
            {
                var t = _parent[v];
                _parent[v] = last;
                v = t;
            }
            return last;
        }

        public int this[int v]
        {
            get { return Find(v); }
            set { Union(v, value); }
        }

        public void Union(int a, int b)
        {
            a = Find(a);
            b = Find(b);
            if (a == b) return;
            if (_rank[a] < _rank[b])
            {
                var t = _rank[a];
                _rank[a] = _rank[b];
                _rank[b] = t;
            }
            _parent[b] = a;
            if (_rank[a] == _rank[b]) _rank[a]++;
        }

        public int GetSetCount()
        {
            var result = 0;
            for (var i = 0; i < Count; i++)
            {
                if (_parent[i] == i) result++;
            }
            return result;
        }

        public DisjointSet Clone()
        {
            var rank = new int[Count];
            _rank.CopyTo(rank, 0);
            var parent = new int[Count];
            _parent.CopyTo(parent, 0);
            return new DisjointSet(Count, parent, rank);
        }

        public override string ToString()
        {
            return string.Join(",", _parent.Take(50));
        }
    }

    public class Matrix
    {
        public static Matrix Create(int i, int j)
        {
            var m = new Matrix(i, j);
            return m;
        }

        public static Matrix Create(int i)
        {
            var m = new Matrix(i, i);
            return m;
        }

        public long Modulo { get; set; }

        private readonly int _width;
        private readonly int _height;
        private readonly long[,] _data;
        public int Width{get { return _width; }}
        public int Height{get { return _height; }}

        private Matrix(int i, int j)
        {
            Modulo = 1000000000000000000L;
            _width = j;
            _height = i;
            _data = new long[_height, _width];
        }

        public static Matrix operator *(Matrix m1, Matrix m2)
        {
            if (m1.Width != m2.Height) throw new InvalidDataException("m1.Width != m2.Height");
            var m = Create(m2.Width, m1.Height);
            m.Modulo = m1.Modulo;
            for (var i=0;i<m2.Width;i++)
                for (var j = 0; j < m1.Height; j++)
                {
                    for (var k = 0; k < m1.Width; k++)
                        m[j, i] += (m1[j, k]*m2[k, i]) % m1.Modulo;
                    m[j, i] %= m1.Modulo;
                }
            return m;
        }

        public static Matrix operator +(Matrix m1, Matrix m2)
        {
            var m = m1.Clone();
            for (var i=0;i<m2.Width;i++)
                for (var j = 0; j < m1.Height; j++)
                    m[j, i] = (m[j, i] + m2[j, i]) % m1.Modulo;
            return m;
        }

        public static Matrix operator -(Matrix m1, Matrix m2)
        {
            var m = m1.Clone();
            for (var i=0;i<m2.Width;i++)
                for (var j = 0; j < m1.Height; j++)
                    m[j, i] = (m[j, i] - m2[j, i]) % m1.Modulo;
            return m;
        }

        public static Matrix operator *(Matrix m1, long l)
        {
            var m = m1.Clone();
            for (var i=0;i<m1.Width;i++)
                for (var j=0;j<m1.Height;j++)
                        m[j, i] = (m[j, i] * l) % m.Modulo;
            return m;
        }

        public static Matrix operator *(long l, Matrix m1)
        {
            return m1*l;
        }

        public static Matrix operator +(Matrix m1, long l)
        {
            var m = m1.Clone();
            for (var i = 0; i < m1.Width; i++)
                    m[i, i] = (m[i, i] + l) % m.Modulo;
            return m;
        }

        public static Matrix operator +(long l, Matrix m1)
        {
            return m1 + l;
        }

        public static Matrix operator -(Matrix m1, long l)
        {
            return m1 + (-l);
        }

        public static Matrix operator -(long l, Matrix m1)
        {
            var m = m1.Clone() * -1;
            return m + l;
        }

        public Matrix BinPower(long l)
        {
            var n = 1;
            var m = Clone();
            var result = new Matrix(m.Height, m.Width) + 1;
            result.Modulo = m.Modulo;
            while (l != 0)
            {
                var i = l & ~(l - 1);
                l -= i;
                while (n < i)
                {
                    m = m*m;
                    n <<= 1;
                }
                result *= m;
            }
            return result;
        }

        public void Fill(long l)
        {
            l %= Modulo;
            for (var i = 0; i < _height; i++)
                for (var j = 0; j < _width; j++)
                    _data[i, j] = l;
        }

        public Matrix Clone()
        {
            var m = new Matrix(_width, _height);
            Array.Copy(_data, m._data, _data.Length);
            m.Modulo = Modulo;
            return m;
        }

        public long this[int i, int j]
        {
            get { return _data[i, j]; }
            set { _data[i, j] = value % Modulo; }
        }
    }
}

namespace Codeforces.TaskB
{
    public class Task
    {
        public static void Main()
        {
            var task = new Task();
            task.Solve();
        }

        void Solve()
        {
            long n, m;
            Input.Next(out n);
            var A = new Point[n];
            for (var i = 0; i < n; i++) Input.Next(out A[i].X, out A[i].Y);

            Input.Next(out m);
            var B = new Point[m];
            for (var i = 0; i < m; i++) Input.Next(out B[i].X, out B[i].Y);

            var C = A[0];

            for (var i = 0; i < n; i++)
            {
                A[i].X -= C.X;
                A[i].Y -= C.Y;
            }
            for (var i = 0; i < m; i++)
            {
                B[i].X -= C.X;
                B[i].Y -= C.Y;
            }
            // p1 = (0, 1)
            // p2 = (1, 0)
            // p3 = (-1, 0)
            // [p1, p2] = -1
            // [p1, p3] = 1
            Func<Point, Point, bool> isLeft = (p1, p2) => p1.X*p2.Y - p1.Y*p2.X > 0;
            Func<Point, Point, bool> isRight = (p1, p2) => p1.X*p2.Y - p1.Y*p2.X < 0;

            foreach (var b in B)
            {
                var l = 1L;
                var r = n - 1;

                if (!isRight(A[l], b) || !isLeft(A[r], b))
                {
                    Console.WriteLine("NO");
                    return;
                }

                while (r > l + 1)
                {
                    var i = (l + r)/2;
                    if (isLeft(A[i], b))
                        r = i;
                    else
                        l = i;
                }

                var p1 = A[l + 1] - A[l];
                var p2 = b - A[l];
                if (isRight(p1, p2)) continue;
                Console.WriteLine("NO");
                return;
            }
            Console.WriteLine("YES");
        }

        private struct Point
        {
            public long X;
            public long Y;

            public static Point operator -(Point p1, Point p2)
            {
                Point p;
                p.X = p1.X - p2.X;
                p.Y = p1.Y - p2.Y;
                return p;
            }

            public override string ToString()
            {
                return string.Format("({0},{1})", X, Y);
            }
        }
    }

}


A bracket sequence is a string, containing only characters "(", ")", "[" and "]".A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition.You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.

The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters.

In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.

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

namespace Saba
{
    public class Hello1
    {
        public static void Main()
        {
            char[] a = Console.ReadLine().ToCharArray();
            List<char> stack = new List<char>();
            List<int> inds = new List<int>();
            List<int> pos = new List<int>();
            int first = 0, last = 0, max = 0, sq = 0;
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] == '(' || a[i] == '[')
                {
                    stack.Add(a[i]);
                    inds.Add(i);
                }
                else
                {
                    if (stack.Count > 0)
                    {
                        if ((a[i] == ')' && stack.Last() == '(') || (a[i] == ']' && stack.Last() == '['))
                        {
                            if (pos.Count > 0)
                            {
                                if (pos.Last() == inds.Last() - 1) { pos[pos.Count - 1] = i; goto next; }
                            }
                            pos.Add(inds.Last());
                            pos.Add(i);
                        next:
                            for (int j = pos.Count - 2; j >= 0; j -= 2)
                            {
                                if (pos[j] > inds.Last()) { pos.RemoveAt(j); pos.RemoveAt(j); j += 2; }
                                else if (pos[j] < inds.Last()) { break; }
                            }
                            stack.RemoveAt(stack.Count - 1);
                            inds.RemoveAt(inds.Count - 1);
                        }
                        else { stack.Clear(); inds.Clear(); }
                    }
                    else { stack.Clear(); inds.Clear(); }
                }
            }
            for (int i = 1; i < pos.Count - 1; i += 2)
            {
                if (pos[i] + 1 == pos[i + 1])
                {
                    pos.RemoveAt(i); pos.RemoveAt(i); i -= 2;
                }
            }
            for (int i = 0; i < pos.Count; i += 2)
            {
                sq = 0;
                for (int j = pos[i]; j < pos[i + 1]; j++) { if (a[j] == '[') { sq++; } }
                if (max < sq) { max = sq; first = pos[i]; last = pos[i + 1]; }
            }
            Console.WriteLine(max);
            if (max > 0) for (int i = first; i <= last; i++) Console.Write(a[i]);
        }
    }
}


Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t + 1, unless there are more travellers arriving at time t + 1 to the same planet.Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.

The first line contains two space-separated integers: n (2 ≤ n ≤ 105), the number of planets in the galaxy, and m (0 ≤ m ≤ 105) — the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1 ≤ ci ≤ 104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection. Then n lines follow: the i-th line contains an integer ki (0 ≤ ki ≤ 105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0 ≤ tij < 109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.

Print a single number — the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.

NoteIn the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then — to planet 4, then he spends a total of only 2 + 5 = 7 seconds.In the second sample one can't get from planet 1 to planet 3 by moving through stargates.

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

namespace Codeforces
{
    class B
    {
        private static ThreadStart s_threadStart = new B().Go;
        private static bool s_time = false;

        public class Heap<T> where T : IComparable<T>
        {
            public Heap() : this(false) { }
            public Heap(ICollection<T> collection) : this(collection, false) { }
            public Heap(ICollection<T> collection, bool minHeap)
                : this(collection.Count, minHeap)
            {
                foreach (T t in collection)
                    Push(t);
            }
            public Heap(bool minHeap) : this(16, minHeap) { }
            public Heap(int capacity) : this(capacity, false) { }
            public Heap(int capacity, bool minHeap)
            {
                int cap = 2;
                while (cap < capacity) cap <<= 1;

                heap = new T[cap + 1];
                size = 0;
                this.minHeap = minHeap;
            }

            public int Count { get { return size; } }

            public bool IsEmpty() { return size < 1; }

            public T Peek()
            {
                if (size < 1)
                    throw new ApplicationException("The heap is empty!");
                return heap[1];
            }

            public virtual T Pop()
            {
                if (size < 1)
                    throw new ApplicationException("The heap is empty!");
                T max = Peek();
                heap[1] = heap[size--];
                inverse[heap[1]] = 1;
                Heapify(1);
                inverse.Remove(max);
                return max;
            }

            public virtual void Push(T value)
            {
                if (++size > heap.Length - 1)
                    Array.Resize<T>(ref heap, heap.Length << 1);
                int i = size;
                while (i > 1 && ((!minHeap && heap[P(i)].CompareTo(value) < 0) || (minHeap && heap[P(i)].CompareTo(value) > 0)))
                {
                    heap[i] = heap[P(i)];
                    inverse[heap[i]] = i;
                    i = P(i);
                }
                heap[i] = value;
                inverse[value] = i;
            }

            public virtual T PopPush(T value)
            {
                if (size < 1)
                    throw new ApplicationException("The heap is empty!");
                T max = Peek();
                heap[1] = value;
                inverse[value] = 1;
                Heapify(1);
                return max;
            }

            protected void Update(T old, T value)
            {
                int i = inverse[value];
                if ((!minHeap && heap[i].CompareTo(value) > 0) || (minHeap && heap[i].CompareTo(value) < 0))
                {
                    heap[i] = value;
                    inverse[value] = i;
                    Heapify(i);
                }
                else
                {
                    heap[i] = value;
                    while (i > 1 && ((!minHeap && heap[i].CompareTo(heap[P(i)]) > 0) || (minHeap && heap[i].CompareTo(heap[P(i)]) < 0)))
                    {
                        Swap(i, P(i));
                        i = P(i);
                    }
                }
            }

            private int P(int i)
            {
                return i / 2;
            }
            private int L(int i)
            {
                return 2 * i;
            }
            private int R(int i)
            {
                return 2 * i + 1;
            }
            private void Heapify(int i)
            {
                int max = i;
                int l = L(i);
                int r = R(i);
                if (l <= size && ((!minHeap && heap[l].CompareTo(heap[i]) > 0) || (minHeap && heap[l].CompareTo(heap[i]) < 0)))
                    max = l;
                if (r <= size && ((!minHeap && heap[r].CompareTo(heap[max]) > 0) || (minHeap && heap[r].CompareTo(heap[max]) < 0)))
                    max = r;
                if (max != i)
                {
                    Swap(i, max);
                    Heapify(max);
                }
            }

            private void Swap(int i, int j)
            {
                T ti = heap[i];
                T tj = heap[j];
                heap[j] = ti;
                heap[i] = tj;
                inverse[ti] = j;
                inverse[tj] = i;
            }

            private T[] heap;
            private Dictionary<T, int> inverse = new Dictionary<T, int>();
            private int size;
            private bool minHeap;
        }

        public class HeapNode<D, P> : IComparable<HeapNode<D, P>> where P : IComparable

        {
            public HeapNode(D data, P priority)
            {
                this.Data = data;
                this.Priority = priority;
            }

            public D Data;
            public P Priority;

            public int CompareTo(HeapNode<D, P> other)
            {
                return Priority.CompareTo(other.Priority);
            }

            public override string ToString()
            {
                return string.Format("{0} ({1})", Data, Priority);
            }
        }

        public class Heap<D, P> : Heap<HeapNode<D, P>> where P : IComparable

        {
            public Heap() : base() { }
            public Heap(bool minHeap) : base(minHeap) { }
            public Heap(int capacity) : base(capacity) { }
            public Heap(int capacity, bool minHeap) : base(capacity, minHeap) { }

            public override HeapNode<D, P> Pop()
            {
                var popped = base.Pop();
                lookup.Remove(popped.Data);
                return popped;
            }
            public override void Push(HeapNode<D, P> value)
            {
                lookup[value.Data] = value;
                base.Push(value);
            }

            public override HeapNode<D, P> PopPush(HeapNode<D, P> value)
            {
                lookup[value.Data] = value;
                var popped = base.PopPush(value);
                lookup.Remove(popped.Data);
                return popped;
            }

            public D PeekData() { return Peek().Data; }
            public P PeekPriority() { return Peek().Priority; }
            public void Push(D data, P priority) { Push(new HeapNode<D, P>(data, priority)); }
            public HeapNode<D, P> PopPush(D data, P priority) { return PopPush(new HeapNode<D, P>(data, priority)); }

            public void Update(D data, P priority)
            {
                if (lookup.ContainsKey(data))
                {
                    var node = lookup[data];
                    node.Priority = priority;
                    Update(node, node);
                }
            }

            public bool Contains(D data)
            {
                return lookup.ContainsKey(data);
            }

            public bool TryGetPriority(D data, out P priority)
            {
                HeapNode<D, P> node;
                bool result = lookup.TryGetValue(data, out node);
                priority = node.Priority;
                return result;
            }

            private Dictionary<D, HeapNode<D, P>> lookup = new Dictionary<D, HeapNode<D, P>>();
        }

        private void Go()
        {
            int n = GetInt();
            int m = GetInt();
            List<Tuple<int, int>>[] adj = new List<Tuple<int, int>>[n];
            for (int i = 0; i < n; i++)
            {
                adj[i] = new List<Tuple<int, int>>();
            }
            for (int i = 0; i < m; i++)
            {
                int a = GetInt()-1;
                int b = GetInt()-1;
                int c = GetInt();

                adj[a].Add(new Tuple<int, int>(b, c));
                adj[b].Add(new Tuple<int, int>(a, c));
            }
            Dictionary<int, int>[] occupied = new Dictionary<int, int>[n];
            for (int i = 0; i < n; i++)
            {
                occupied[i] = new Dictionary<int,int>();
                int k = GetInt();
                if (k > 0)
                {
                    int[] xs = new int[k];
                    for (int j = 0; j < k; j++)
                    {
                        xs[j] = GetInt();
                    }
                    int val = xs[k - 1] + 1;
                    occupied[i][xs[k - 1]] = val;
                    for (int j = k - 2; j >= 0; j--)
                    {
                        if (xs[j] + 1 < xs[j + 1]) val = xs[j] + 1;
                        occupied[i][xs[j]] = val;
                    }
                }
            }

            //--
            int source = 0;
            int inf = int.MaxValue;
            int N = adj.Length;
            int[] dist = new int[N];
            int[] pred = new int[N];
            for (int i = 0; i < N; i++)
                dist[i] = inf;
            dist[source] = 0;

            Heap<int, int> heap = new Heap<int, int>(N, true);
            heap.Push(source, 0);

            while (!heap.IsEmpty())
            {
                int u = heap.PeekData();
                if (dist[u] != heap.Pop().Priority) continue;
                int addon = dist[u];
                if (occupied[u].ContainsKey(dist[u])) addon = occupied[u][dist[u]];
                foreach (var tuple in adj[u])
                {
                    int v = tuple.Item1;
                    int uvWeight = tuple.Item2;
                    if (dist[v] > addon + uvWeight)
                    {
                        dist[v] = addon + uvWeight;
                        pred[v] = u;
                        heap.Push(v, dist[v]);
                    }
                }
            }
            //--

            int ans = dist[n-1];
            if (ans == int.MaxValue) ans = -1;
            Wl(ans);
        }

        #region Template

        public static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            Thread main = new Thread(new ThreadStart(s_threadStart), 512 * 1024 * 1024);
            timer.Start();
            main.Start();
            main.Join();
            timer.Stop();
            if (s_time)
                Wl(timer.ElapsedMilliseconds);
        }

        private static IEnumerator<string> ioEnum;
        private static string GetString()
        {
            while (ioEnum == null || !ioEnum.MoveNext())
            {
                ioEnum = Console.ReadLine().Split().AsEnumerable().GetEnumerator();
            }

            return ioEnum.Current;
        }

        private static int GetInt()
        {
            return int.Parse(GetString());
        }

        private static long GetLong()
        {
            return long.Parse(GetString());
        }

        private static double GetDouble()
        {
            return double.Parse(GetString());
        }

        private static List<int> GetIntArr(int n)
        {
            List<int> ret = new List<int>(n);
            for (int i = 0; i < n; i++)
            {
                ret.Add(GetInt());
            }
            return ret;
        }

        private static void Wl<T>(T o)
        {
            if (o is double)
            {
                Wld((o as double?).Value, "");
            }
            else if (o is float)
            {
                Wld((o as float?).Value, "");
            }
            else
                Console.WriteLine(o.ToString());
        }

        private static void Wl<T>(IEnumerable<T> enumerable)
        {
            Wl(string.Join(" ", enumerable.Select(e => e.ToString()).ToArray()));
        }

        private static void Wld(double d, string format)
        {
            Wl(d.ToString(format, CultureInfo.InvariantCulture));
        }

        public struct Tuple<T, K> : IComparable<Tuple<T, K>>
            where T : IComparable<T>
            where K : IComparable<K>
        {
            public T Item1;
            public K Item2;

            public Tuple(T t, K k)
            {
                Item1 = t;
                Item2 = k;
            }

            public override bool Equals(object obj)
            {
                var o = (Tuple<T, K>)obj;
                return o.Item1.Equals(Item1) && o.Item2.Equals(Item2);
            }

            public override int GetHashCode()
            {
                return Item1.GetHashCode() ^ Item2.GetHashCode();
            }

            public override string ToString()
            {
                return "(" + Item1 + " " + Item2 + ")";
            }

            #region IComparable<Tuple<T,K>> Members

            public int CompareTo(Tuple<T, K> other)
            {
                int ret = Item1.CompareTo(other.Item1);
                if (ret != 0) return ret;
                return Item2.CompareTo(other.Item2);
            }

            #endregion
        }

        #endregion
    }
}


This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.

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

namespace CodeForces
{
    public class PriorityQueue<TPriority, TItem>
    {
        readonly SortedDictionary<TPriority, Queue<TItem>> _subqueues;
        private int _count = 0;
        public int Count { get { return _count; } }

        public PriorityQueue(IComparer<TPriority> priorityComparer)
        {
            _subqueues = new SortedDictionary<TPriority, Queue<TItem>>(priorityComparer);
        }

        public PriorityQueue() : this(Comparer<TPriority>.Default) { }

        public void Enqueue(TPriority priority, TItem item)
        {
            if (!_subqueues.ContainsKey(priority))
            {
                _subqueues.Add(priority, new Queue<TItem>());
            }

            _subqueues[priority].Enqueue(item);

            _count++;
        }

        public TItem Peek()
        {
            if (HasItems)
                return _subqueues.First().Value.Peek();
            else
                throw new InvalidOperationException("The queue is empty");
        }

        public bool HasItems
        {
            get { return _subqueues.Any(); }
        }

        public TItem Dequeue()
        {
            if (_subqueues.Any())
            {
                KeyValuePair<TPriority, Queue<TItem>> first = _subqueues.First();
                TItem nextItem = first.Value.Dequeue();
                if (!first.Value.Any())
                {
                    _subqueues.Remove(first.Key);
                }
                _count--;
                return nextItem;
            }
            else
                throw new InvalidOperationException("The queue is empty");
        }
    }

    public class LeastCostBracketSequence
    {
        class Cost
        {
            public int Index { get; set; }
            public int Left { get; set; }
            public int Right { get; set; }

            public int GetWeight()
            {
                return Right - Left;
            }
        }

        class CostComparer : IComparer<int>
        {
            public int Compare(int x, int y)
            {
                return -(x.CompareTo(y));
            }
        }

        public static void Main(string[] args)
        {
            var inputs = Console.ReadLine();
            StringBuilder result = new StringBuilder();
            int balance = 0;
            long totalWeight = 0;
            var costs = new PriorityQueue<int, Cost>(new CostComparer());

            for (int i = 0; i < inputs.Length; i++)
            {
                switch (inputs[i])
                {
                    case '(':
                        result.Append(inputs[i]);
                        balance++;
                        break;
                    case ')':
                        result.Append(inputs[i]);
                        balance--;
                        break;
                    case '?':
                        int[] inputs2 = Array.ConvertAll(Console.ReadLine().Split(new[] { ' ' }), int.Parse);
                        var cost = new Cost {Index = i, Left = inputs2[0], Right = inputs2[1]};
                        costs.Enqueue(cost.GetWeight(), cost);
                        result.Append(')');
                        balance--;
                        totalWeight += cost.Right;
                        break;
                }
                if (balance < 0)
                {
                    if (costs.Count == 0)
                    {
                        break;
                    }
                    else
                    {
                        var top = costs.Dequeue();
                        totalWeight += top.Left;
                        totalWeight -= top.Right;
                        result[top.Index] = '(';
                        balance += 2;
                    }
                }
            }
            if (balance != 0)
            {
                Console.WriteLine("-1");
            }
            else
            {
                Console.WriteLine(totalWeight);
                Console.WriteLine(result);
            }
        }
    }
}


Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges.

The first line of input contains two integers n and m (1 ≤ n ≤ 19, 0 ≤ m) – respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1 ≤ a, b ≤ n, a ≠ b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices.

Output the number of cycles in the given graph.

NoteThe example graph is a clique and contains four cycles of length 3 and three cycles of length 4.

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

class Program
{

    void solve()
    {
        int n = nextInt();
        bool[,] g = new bool[n, n];
        int m = nextInt();
        for (int i = 0; i < m; i++)
        {
            int a = nextInt();
            int b = nextInt();
            a--;
            b--;
            g[a, b] = g[b, a] = true;

        }
        long ret = 0;
        for (int f = 0; f < n; f++)
        {
            long[,] dp = new long[f, 1 <<f];
            for(int i=0;i<f;i++)
                if(g[f,i])
                    dp[i,1<<i]=1;
            for (int set = 1; set < (1 <<f); set++)
                for (int i = 0; i < f; i++)
                    if ((set & (1 << i)) > 0)
                        for (int j = 0; j < f; j++)
                            if ((set & (1 << j)) > 0 && g[i, j])
                                dp[i, set] += dp[j, set ^ (1 << i)];
            for(int i=0;i<f;i++)
                if(g[f,i])
                    for(int set=1;set<(1<<f);set++)
                        if ((set & (1 << i)) > 0 && (set!=1<<i))
                        {
                            long num = dp[i, set];
                            ret += num;
                        }

        }
        Console.WriteLine(ret / 2);

    }

    //

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

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


The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them. For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to . The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.

The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.

Print the single number — the minimum number of moves in the sought path.

NotePicture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.

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

namespace ProgrammingContest.Codeforces.Round47
{
    class C
    {
        static bool LeftRotate(Pair<long, long>[] ps, int len)
        {
            int i = len - 2;
            long x1 = ps[i - 1].first, x2 = ps[i].first, x3 = ps[i + 1].first,
                y1 = ps[i-1].second, y2 = ps[i].second, y3 = ps[i+1].second;
            long cp = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1);
            return cp >= 0;
        }

        static Pair<long, long>[] ConvexHull(Pair<long, long>[] ps)
        {
            if(ps.Length < 3) return ps;
            int ul = 0;
            Pair<long, long>[] upper = new Pair<long, long>[ps.Length];
            upper[ul++] = ps[0]; upper[ul++] = ps[1];
            for (int i = 2; i < ps.Length; i++)
            {
                upper[ul++] = ps[i];
                while (ul >= 3 && LeftRotate(upper, ul))
                {
                    upper[ul - 2] = upper[ul - 1];
                    ul--;
                }
            }

            int ll = 0;
            var lower = new Pair<long, long>[ps.Length];
            lower[ll++] = ps[ps.Length - 1]; lower[ll++] = ps[ps.Length - 2];
            for (int i = ps.Length-3; i >= 0; i--)
            {
                lower[ll++] = ps[i];
                while (ll >= 3 && LeftRotate(lower, ll))
                {
                    lower[ll-2] = lower[ll-1];
                    ll--;
                }
            }
            Pair<long, long>[] res = new Pair<long, long>[ul + ll - 2];
            int p = 0;
            for (int i = 0; i < ul; i++) res[p++] = upper[i];
            for (int i = 1; i < ll - 1; i++) res[p++] = lower[i];
            return res;
        }

        public static void Main()
        {
            int n = int.Parse(Console.ReadLine());
            var ps = new Pair<long, long>[n];
            for (int i = 0; i < n; i++)
            {
                int[] xy = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
                ps[i].first = xy[0];
                ps[i].second = xy[1];
            }

            Array.Sort(ps);
            var ps2 = ConvexHull(ps);
#if false
            Console.WriteLine();
            for (int i = 0; i < ps2.Length; i++)
                Console.WriteLine("{0} {1}", ps2[i].first, ps2[i].second);
#endif
            long[] dx = new long[] { 0, 0, -1, 1 }, dy = new long[] { -1, 1, 0, 0 };
            var ps3 = new Pair<long, long>[ps2.Length * 4];
            for (int i = 0; i < ps2.Length; i++)
                for (int j = 0; j < 4; j++)
                {
                    ps3[i * 4 + j].first = ps2[i].first + dx[j];
                    ps3[i * 4 + j].second = ps2[i].second + dy[j];
                }

            Array.Sort(ps3);
            var ps4 = ConvexHull(ps3);

            long res = 0;
            for (int i = 0, m = ps4.Length; i < m; i++)
            {
                long dx_ = Math.Abs(ps4[i].first - ps4[(i + 1) % m].first),
                    dy_ = Math.Abs(ps4[i].second - ps4[(i + 1) % m].second);
                res += Math.Max(dx_, dy_);
            }
            Console.WriteLine(res);
        }

        #region Pair
        public static class Pair
        {
            public static Pair<T1, T2> Create<T1, T2>(T1 t1, T2 t2)
                where T1 : IComparable<T1>, IEquatable<T1>
                where T2 : IComparable<T2>, IEquatable<T2>
            {
                return new Pair<T1, T2>(t1, t2);
            }
        }

        public struct Pair<T1, T2> : IComparable<Pair<T1, T2>>
            where T1 : IComparable<T1>, IEquatable<T1>
            where T2 : IComparable<T2>, IEquatable<T2>
        {
            public T1 first;
            public T2 second;

            public Pair(T1 t1, T2 t2)
            {
                first = t1;
                second = t2;
            }

            public static bool operator <(Pair<T1, T2> lhs, Pair<T1, T2> rhs)
            {
                int comp = lhs.first.CompareTo(rhs.first);
                if (comp < 0 || comp == 0 && lhs.second.CompareTo(rhs.second) < 0) return true;
                return false;
            }

            public static bool operator >(Pair<T1, T2> lhs, Pair<T1, T2> rhs)
            {
                return !(lhs < rhs || lhs == rhs);
            }

            public static bool operator ==(Pair<T1, T2> lhs, Pair<T1, T2> rhs)
            {
                return lhs.first.Equals(rhs.first) && lhs.second.Equals(rhs.second);
            }

            public static bool operator !=(Pair<T1, T2> lhs, Pair<T1, T2> rhs)
            {
                return !(lhs == rhs);
            }

            public int CompareTo(Pair<T1, T2> p)
            {
                if (this < p) return -1;
                if (this > p) return 1;
                return 0;
            }

            public override bool Equals(object obj)
            {
                return base.Equals(obj);
            }
            public override int GetHashCode()
            {
                return base.GetHashCode();
            }
        }
        #endregion
    }
}


Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.

The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.

Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.

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

namespace ProgrammingContest.Codeforces.Round48
{
    class Rational
    {
        public long bunsi, bunbo;
        public Rational(long bunbo, long bunsi)
        {
            long g = gcd(bunsi, bunbo);
            if (g != 0)
            {
                this.bunsi = bunsi / g;
                this.bunbo = bunbo / g;
            }
            if (this.bunbo < 0)
            {
                this.bunbo = -this.bunbo;
                this.bunsi = -this.bunsi;
            }
        }

        public bool eq(Rational r) { return bunsi == r.bunsi && bunbo == r.bunbo; }
        static long gcd(long n, long r) { if (r == 0) return n; return gcd(r, n % r); }
    }
    class D
    {
        static int n;
        static int[] xs;

        static long gcd(long n, long r) { if (r == 0) return n; return gcd(r, n % r); }

        static bool ok(Rational r, long a, long b)
        {
            long c = r.bunsi*a;
            long g = gcd(c, r.bunbo);
            if (g == 0) return b == 0;
            if (r.bunbo != g) return false;
            return c / g == b;
        }

        static int check(int start, Rational r, bool rec)
        {
            if (r.bunbo == 0 && r.bunsi != 0) return 2;
            //Console.WriteLine("{0} / {1}", r.bunsi, r.bunbo);
            for (int i = start; i < n - 1; i++)
            {
                if (ok(r, xs[i], xs[i + 1])) continue;
                if (!rec) return 2;
                if (i + 2 >= n) return 1;
                int res = 2;
                if (i == 0 && ok(r, xs[i + 1], xs[i + 2]) || ok(r, xs[i], xs[i + 2]))
                {
                    res = Math.Min(res, check(i + 2, r, false) + 1);
                }
                return res;
            }
            return 0;
        }

        public static void Main()
        {
            Scanner scanner = Scanner.FromConsole();
            n = scanner.NextInt();
            xs = scanner.NextInts(n);
            //Array.Sort(xs, (a, b) => Math.Abs(a) - Math.Abs(b));
            if (n == 1)
            {
                Console.WriteLine(0);
                return;
            }
            if (n == 2)
            {
                Console.WriteLine(xs[0] != 0 || xs[1] == 0 ? 0 : 1);
                return;
            }
            int res = check(0, new Rational(xs[0], xs[1]),true);
            res = Math.Min(res, check(0, new Rational(xs[0], xs[2]), true));
            res = Math.Min(res, check(0, new Rational(xs[1], xs[2]), true));
            Console.WriteLine(res);
            return;
        }

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

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

            public enum Option { Buffering, NoBuffering }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

            public enum Option { Buffering, NoBuffering }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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.

The first line contains number n, which is the number of knights at the round table (3 ≤ n ≤ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.

Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".

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

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

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

            nn = new int[n];
            for (int i = 0; i < n; i++)
            {
                nn[i] = Next();
            }

            for (int i = 1; i*i <= n; i++)
            {
                if (n%i == 0)
                {
                    if (n/i >= 3 && Check(i))
                    {
                        writer.WriteLine("YES");
                        writer.Flush();
                        return;
                    }
                    if (i >= 3 && i*i != n && Check(n/i))
                    {
                        writer.WriteLine("YES");
                        writer.Flush();
                        return;
                    }
                }
            }

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

        private static bool Check(int k)
        {
            for (int i = 0; i < k; i++)
            {
                bool ok = true;
                for (int j = i; j < nn.Length; j += k)
                {
                    if (nn[j] == 0)
                    {
                        ok = false;
                        break;
                    }
                }
                if (ok)
                    return true;
            }
            return false;
        }

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


Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than x and not less than 2 items in his inventory. A new patch for the game appeared to view inventory in n different modes. Displaying in mode i is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly ai items. In addition, each mode shows how many pages bi is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it?Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size.Knowing the number of ai, x and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers ai, x and he is able to know number bi after viewing items in mode i.

The first line contains two integers n and x (0 ≤ n ≤ 105, 2 ≤ x ≤ 109). The second line contains integers ai (1 ≤ ai ≤ 109). Some numbers among all ai may be equal.

Output the fewest amount of modes required to uniquely determine amount of items in the inventory. If there is no solution output  - 1.

NoteIn the second example Vasya is not able to determine items count uniquely because 3 items, as well as 4 items, can be displayed on two pages.

using System;
using System.Collections.Generic;

public class Program {
    private int n;
    private int[] numbers;

    public void Solve() {
        string[] data;
        data = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        n = int.Parse(data[1]);
        data = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        numbers = new int[data.Length];
        for (int i = 0; i < numbers.Length; ++i)
            numbers[i] = int.Parse(data[i]);
        Console.WriteLine(computeMinCost());
    }

    private int computeMinCost() {
        Array.Sort(numbers);
        if (numbers.Length > 0 && numbers[0] == 1)
            return n == 2 ? 0 : 1;
        else if (n >= limit)
            return -1;
        int cost = 0, index = 0;
        foreach (int prime in primes) {
            if (prime >= n)
                break;
            while (index < numbers.Length && numbers[index] < prime)
                ++index;
            if (index == numbers.Length || numbers[index] != prime)
                return -1;
            ++cost;
        }
        return cost;
    }

    private static int limit = 1299744;
    private static bool[] isPrime;
    private static List<int> primes;

    private static void computePrimes() {
        isPrime = new bool[limit];
        for (int i = 2; i < limit; ++i)
            isPrime[i] = true;
        primes = new List<int>();
        for (int i = 2; i < limit; ++i) {
            if (isPrime[i])
                primes.Add(i);
            foreach (int prime in primes) {
                if (i * prime >= limit)
                    break;
                isPrime[i * prime] = false;
                if (i % prime == 0)
                    break;
            }
        }
    }

    public static void Main() {
        computePrimes();
        new Program().Solve();
    }
}


Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.  It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.

The first line contains two integers n and m (2 ≤ n, m ≤ 106).

Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).

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

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = Console.ReadLine();

            int n = int.Parse(s1.Split(' ')[0]) - 1;
            int m = int.Parse(s1.Split(' ')[1]) - 1;

            int min = m;

            if (n < m)
            {
                min = n;
                n = m;
                m = min;
            }

            byte[] poss = new byte[min + 1];

            for (int i = 0; i < poss.Length; i++)
                poss[i] = 1;

            for (int i = 0; i <= min; i++)
            {
                if (poss[i] == 1)
                {
                    int y = i;
                    int dy = 2 * n % (2 * m);

                    do
                    {
                        y += dy;
                        int k = 0;
                        if (y <0) k = -1;
                        else k = 1;
                        dy *= k * Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((Math.Abs(y) - 1) / m) % 2)));
                        y = (Math.Abs(y) / m) % 2 * m + Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((Math.Abs(y) - 1) / m) % 2))) * Math.Abs(y % m);
                        //dy *= Convert.ToInt32(Math.Pow((-1.0), Convert.ToDouble(((y - 1) / m) % 2 - 1)));
                        if (poss[y] == 1 && y != i)
                            poss[y] = 0;
                    } while (!((y == i && dy >= 0) || (y == 0)));
                }
            }

            int cou = 0;

            for (int i = 0; i < poss.Length; i++)
                if (poss[i] == 1)
                    cou++;

            Console.WriteLine(cou.ToString());

            Console.ReadKey();
        }

    }
}


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

The first line contains an integer n (2 ≤ n ≤ 105), n is the number of marks in Polycarp's Journal. The second line contains two positive integers a, b (1 ≤ a, b ≤ n - 1, a + b = n). The third line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 5), they are Polycarp's marks.

Print the sequence of integers f1, f2, ..., fn, where fi (1 ≤ fi ≤ 2) is the number of a subject to which the i-th mark should be attributed. If there are several possible solutions, then print such that the sequence f1, f2, ..., fn is the smallest lexicographically. The sequence p1, p2, ..., pn is lexicographically less than q1, q2, ..., qn if there exists such j (1 ≤ j ≤ n) that pi = qi for all 1 ≤ i < j, аnd pj < qj.

NoteIn the first sample the average score in the first subject is equal to 4, and in the second one — to 4.5. The total average score is 8.5.

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


Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?

The first line contains the only integer n (0≤n≤10^100000). It is guaranteed that n doesn't contain any leading zeroes.

Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.

In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991→19→10→1. After three transformations the number becomes one-digit.

x=gets.to_i.to_s
i = 0
while x.size > 1 do
  x=x.split('').map(&:to_i).sum.to_s
  i+=1
end
p i