// 68 ms    4811 kb

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;

namespace sar_cs
{
    public class Program
    {
        public class Parser
        {
            const int BufSize = 25000;
            TextReader s;
            char[] buf = new char[BufSize];
            int bufPos;
            int bufDataSize;
            bool eos;   // eos read to buffer
            int lastChar = -2;
            int nextChar = -2;
            StringBuilder sb = new StringBuilder();

            void FillBuf()
            {
                if (eos) return;
                bufDataSize = s.Read(buf, 0, BufSize);
                if (bufDataSize == 0) eos = true;
                bufPos = 0;
            }

            int Read()
            {
                if (nextChar != -2)
                {
                    lastChar = nextChar;
                    nextChar = -2;
                }
                else
                {
                    if (bufPos == bufDataSize) FillBuf();
                    if (eos) lastChar = -1;
                    else lastChar = buf[bufPos++];
                }
                return lastChar;
            }

            void Back()
            {
                if (lastChar == -2) throw new Exception();  // no chars were ever read
                nextChar = lastChar;
            }

            public Parser()
            {
                s = Console.In;
            }

            public int ReadInt()
            {
                int res = 0;
                int sign = -1;
                int c;
                do { c = Read(); } while (c >= 0 && char.IsWhiteSpace((char)c));
                if (c == '-')
                {
                    sign = -sign;
                    c = Read();
                }
                int len = 0;
                while (c >= 0 && !char.IsWhiteSpace((char)c))
                {
                    if ((uint)(c -= 48) >= 10) throw new InvalidDataException();
                    len++;
                    res = checked(res * 10 - c);
                    c = Read();
                }
                if (len == 0) throw new InvalidDataException();
                Back();
                return checked(res * sign);
            }

            public long ReadLong()
            {
                long res = 0;
                int sign = -1;
                int c;
                do { c = Read(); } while (c >= 0 && char.IsWhiteSpace((char)c));
                if (c == '-')
                {
                    sign = -sign;
                    c = Read();
                }
                int len = 0;
                checked
                {
                    while (c >= 0 && !char.IsWhiteSpace((char)c))
                    {
                        if ((uint)(c -= 48) >= 10) throw new InvalidDataException();
                        len++;
                        res = res * 10 - c;
                        c = Read();
                    }
                    if (len == 0) throw new InvalidDataException();
                    Back();
                    return res * sign;
                }
            }

            public double ReadDouble()
            {
                int c;
                do { c = Read(); } while (c >= 0 && char.IsWhiteSpace((char)c));

                int sign = 1;
                if (c == '-')
                {
                    sign = -1;
                    c = Read();
                }

                sb.Length = 0;
                while (c >= 0 && !char.IsWhiteSpace((char)c))
                {
                    sb.Append((char)c);
                    c = Read();
                }

                Back();
                double res = double.Parse(sb.ToString(), CultureInfo.InvariantCulture);
                return res * sign;
            }

            public string ReadLine()
            {
                int c = Read();
                sb.Length = 0;
                while (c != -1 && c != 13 && c != 10)
                {
                    sb.Append((char)c);
                    c = Read();
                }
                if (c == 13)
                {
                    c = Read();
                    if (c != 10) Back();
                }
                return sb.ToString();
            }

            public bool EOF
            {
                get
                {
                    if (Read() == -1) return true;
                    Back();
                    return false;
                }
            }

            public bool SeekEOF
            {
                get
                {
                L0:
                    int c = Read();
                    if (c == -1) return true;
                    if (char.IsWhiteSpace((char)c)) goto L0;
                    Back();
                    return false;
                }
            }
        }

        static void pe()
        {
            Console.WriteLine("???");
            Environment.Exit(0);
        }

        static void re()
        {
            Environment.Exit(55);
        }

        static int nosol()
        {
            Console.WriteLine("ERROR");
            return 0;
        }

        static Stopwatch sw = Stopwatch.StartNew();

        static StringBuilder sb = new StringBuilder();
        static Random rand = new Random(52345235);

        static void Swap<T>(ref T a, ref T b)
        {
            T t = a;
            a = b;
            b = t;
        }
        const double PI = Math.PI;
        const double PI2 = PI * 2;

        public struct PointD
        {
            public double X, Y;

            public const double eps = 1e-8;

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

            public string ToString(string format)
            {
                return X.ToString(format, CultureInfo.InvariantCulture) + " " + Y.ToString(format, CultureInfo.InvariantCulture);
            }

            public PointD(double x, double y) { X = x; Y = y; }

            public PointD(Program.Parser parser) : this(parser.ReadDouble(), parser.ReadDouble()) { }

            /// <summary>Rotates point clockwise</summary>
            public PointD Rotate(double angle)
            {
                double cos = Math.Cos(angle);
                double sin = -Math.Sin(angle);
                return new PointD(X * cos - Y * sin, X * sin + Y * cos);
            }

            public override bool Equals(object obj)
            {
                if (obj is PointD)
                {
                    PointD otherD = (PointD)obj;
                    return Math.Abs(otherD.X - X) + Math.Abs(otherD.Y - Y) < eps;
                }
                return false;
            }

            public override int GetHashCode()
            {
                throw new NotSupportedException();
                //return X.GetHashCode() ^ Y.GetHashCode();
            }

            public static PointD operator +(PointD p1, PointD p2) { return new PointD(p1.X + p2.X, p1.Y + p2.Y); }
            public static PointD operator -(PointD p1, PointD p2) { return new PointD(p1.X - p2.X, p1.Y - p2.Y); }
            public PointD Add(double dx, double dy) { return new PointD(X + dx, Y + dy); }

            public double Atan2 { get { return Math.Atan2(Y, X); } }

            public double Dist2() { return X * X + Y * Y; }
        }

        public struct VectorD
        {
            public const double eps = 1e-12;
            public double X, Y;

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

            public bool Equals(VectorD other)
            {
                return Math.Abs(X - other.X) + Math.Abs(Y - other.Y) < eps;
            }

            public VectorD(double x, double y)
            {
                X = x; Y = y;
            }

            public VectorD(PointD start, PointD end)
            {
                X = end.X - start.X;
                Y = end.Y - start.Y;
            }

            public static double operator *(VectorD v1, VectorD v2)
            {
                return (v1.Y * v2.X - v1.X * v2.Y);
            }

            public static double ScalarProduct(VectorD v1, VectorD v2)
            {
                return (v1.X * v2.X + v1.Y * v2.Y);
            }

            public double Length { get { return Math.Sqrt(X * X + Y * Y); } }
            public double Length2 { get { return (X * X + Y * Y); } }

            /// <summary>
            /// возвращает угол (-pi;pi], на который надо повернуть v1 чтобы он совпал с v2.
            /// </summary>
            public static double Angle(VectorD v1, VectorD v2)
            {
                double sin = v1 * v2;
                double cos = ScalarProduct(v1, v2);

                if (sin > eps)
                {
                    if (cos > eps) return Math.Atan(sin / cos);
                    else if (cos < -eps) return PI + Math.Atan(sin / cos);
                    else return PI / 2;
                }
                else if (sin < -eps)
                {
                    if (cos > eps) return Math.Atan(sin / cos);
                    else if (cos < -eps) return PI + Math.Atan(sin / cos);
                    else return -PI / 2;
                }
                else
                {
                    if (cos > eps) return 0;
                    else if (cos < -eps) return PI;
                    else throw new Exception("zero vector");
                }
            }
        }

        public static class ConvexHull
        {
            // Notes:
            // pts is not affected.
            // PointD[] can be any indexable type.
            // работает даже для вырожденных случаев.

            static int[] p;
            static PointD[] pts;
            static double[] a;

            class PointComparer : IComparer<int>
            {
                public int Compare(int p1, int p2)
                {
                    double da = a[p1] - a[p2];
                    if (Math.Abs(da) > 1e-9) return Math.Sign(da);
                    return Math.Sign(pts[p1].Dist2() - pts[p2].Dist2());
                }
            }

            public static List<int> Do(PointD[] pts)
            {
                List<int> ch = new List<int>();
                if (pts.Length == 0) return ch;

                ConvexHull.pts = pts;
                p = new int[pts.Length];
                for (int i = 0; i < pts.Length; i++) p[i] = i;

                int m = 0;
                for (int i = 1; i < pts.Length; i++)
                    if (pts[i].Y < pts[m].Y || pts[i].Y == pts[m].Y && pts[i].X < pts[m].X)
                        m = i;
                p[0] = m; p[m] = 0;

                a = new double[pts.Length];
                for (int i = 1; i < pts.Length; i++) a[p[i]] = (pts[p[i]] - pts[m]).Atan2;

                Array.Sort<int>(p, 1, pts.Length - 1, new PointComparer());

                // избавляемся от дубликатов точки m.
                int j;
                for (j = 1; j < pts.Length - 1; j++)
                    if (pts[p[j]].Dist2() == 0) p[j] = -1;
                    else break;

                // "если есть несколько точек с одинаковым углом, то оставляем только самую удалённую."
                // заодно и избавимся от дубликатов.
                for (; j < pts.Length - 1; j++)
                    if (Math.Abs(a[p[j + 1]] - a[p[j]]) < 1e-9)
                        p[j] = -1;

                ch.Add(p[0]);
                j = 1;
                while (ch.Count < 3)
                {
                    if (j == p.Length) return ch;
                    if (p[j++] >= 0) ch.Add(p[j - 1]);
                }

                for (; j < p.Length; j++)
                {
                    while (j < p.Length && p[j] < 0) j++;
                    if (j == pts.Length) return ch;         // вроде никогда не должно сработать

                    while (true)
                    {
                        PointD p1 = pts[ch[ch.Count - 2]];
                        PointD p2 = pts[ch[ch.Count - 1]];
                        PointD p3 = pts[p[j]];
                        var v12 = new VectorD(p2, p1);
                        var v23 = new VectorD(p3, p2);
                        if (v12 * v23 < 0) break;

                        ch.RemoveAt(ch.Count - 1);
                    }
                    ch.Add(p[j]);
                }

                return ch;
            }

            public static void test()
            {
                List<PointD> pts = new List<PointD>();
                pts.Add(new PointD(1, 1));
                pts.Add(new PointD(0, 0));
                pts.Add(new PointD(2, 2));
                pts.Add(new PointD(10, 0));
                var ch = Do(pts.ToArray());
                var chpts = new List<PointD>();
                foreach (var p in ch)
                    chpts.Add(pts[p]);
            }
        }

        static int Main(string[] args)
        {
           Geometry.ConvexHull.test();

            //Console.SetIn(File.OpenText("_input"));
            Parser parser = new Parser();

            int n = parser.ReadInt();
            PointD[] pts = new PointD[n * 4];
            for (int i = 0; i < n; i++)
            {
                PointD p = new PointD(parser);
                pts[i * 4] = p.Add(1, 0);
                pts[i * 4 + 1] = p.Add(-1, 0);
                pts[i * 4 + 2] = p.Add(0, 1);
                pts[i * 4 + 3] = p.Add(0, -1);
            }

            var ch = ConvexHull.Do(pts);
            int res = 0;
            for (int i = 0; i < ch.Count; i++)
            {
                int j = (i + 1) % ch.Count;
                res += Math.Max(
                    Math.Abs((int)(pts[ch[j]].X - pts[ch[i]].X)),
                    Math.Abs((int)(pts[ch[j]].Y - pts[ch[i]].Y)));
            }

            Console.WriteLine(res);
            return 0;
        }
    }
}

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


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

class Program
{
    private static bool Can(int k, string s, int d)
    {
        int prev = 0;
        int pos = 0;
        k -= 2;
        while (true)
        {
            if (k == 0)
            {
                if (s.Length - pos - 2 > d) return false;

                return true;
            }

            k--;
            pos += d + 1;
            if (pos >= s.Length) return true;

            while (pos > prev && s[pos] == '1') pos--;

            if (pos == prev) return false;
        }

        return true;
    }

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

        var s = new string(ReadStringLine());

        if (Can(k, s, 0))
        {
            Console.WriteLine(0);
            return;
        }

        int l = 0;
        int r = n;
        while (r - l > 1)
        {
            var mid = (l + r) / 2;
            if (Can(k, s, mid))
                r = mid;
            else
                l = mid;
        }

        Console.WriteLine(r);
    }

    private const int Mod = 1000000000 + 7;

    #region Data Read
    private static char ReadSign()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (ans == '+' || ans == '-' || ans == '?')
                return (char)ans;
        }
    }

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

    private static List<int>[] ReadGraph(int n, int m)
    {
        List<int>[] g = new List<int>[n];
        for (int i = 0; i < g.Length; i++) g[i] = new List<int>();
        for (int i = 0; i < m; i++)
        {
            int a = RI() - 1;
            int b = RI() - 1;

            g[a].Add(b);
            g[b].Add(a);
        }

        return g;
    }

    private static int[,] ReadGraphAsMatrix(int n, int m)
    {
        int[,] matrix = new int[n + 1, n + 1];
        for (int i = 0; i < m; i++)
        {
            int a = RI();
            int b = RI();
            matrix[a, b] = matrix[b, a] = 1;
        }

        return matrix;
    }

    private static void Sort(ref int a, ref int b)
    {
        if (a > b) Swap(ref a, ref b);
    }

    private static void Swap(ref int a, ref int b)
    {
        int tmp = a;
        a = b;
        b = tmp;
    }

    private const int BufferSize = 1 << 16;
    private static StreamReader consoleReader;
    private static MemoryStream testData;

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

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

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

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

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

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

    private static int[] RIA(int n)
    {
        int[] ans = new int[n];
        for (int i = 0; i < n; i++)
            ans[i] = RI();
        return ans;
    }

    private static long[] RLA(int n)
    {
        long[] ans = new long[n];
        for (int i = 0; i < n; i++)
            ans[i] = RL();
        return ans;
    }

    private static char[] ReadWord()
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (!((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z')));

        List<char> s = new List<char>();
        do
        {
            s.Add((char)ans);
            ans = consoleReader.Read();
        } while ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'));

        return s.ToArray();
    }

    private static char[] ReadString(int n)
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (!((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z')));

        char[] s = new char[n];
        int pos = 0;
        do
        {
            s[pos++] = (char)ans;
            if (pos == n) break;
            ans = consoleReader.Read();
        } while ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'));

        return s;
    }

    private static char[] ReadStringLine()
    {
        int ans;

        do
        {
            ans = consoleReader.Read();
        } while (ans == 10 || ans == 13);

        List<char> s = new List<char>();

        do
        {
            s.Add((char)ans);
            ans = consoleReader.Read();
        } while (ans != 10 && ans != 13 && ans != -1);

        return s.ToArray();
    }

    private static char ReadLetter()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'))
                return (char)ans;
        }
    }
    private static char ReadNonLetter()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (!((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z')))
                return (char)ans;
        }
    }

    private static char ReadAnyOf(IEnumerable<char> allowed)
    {
        while (true)
        {
            char ans = (char)consoleReader.Read();
            if (allowed.Contains(ans))
                return ans;
        }
    }

    private static char ReadDigit()
    {
        while (true)
        {
            int ans = consoleReader.Read();
            if (ans >= '0' && ans <= '9')
                return (char)ans;
        }
    }

    private static int ReadDigitInt()
    {
        return ReadDigit() - (int)'0';
    }

    private static char ReadAnyChar()
    {
        return (char)consoleReader.Read();
    }

    private static string DoubleToString(double x)
    {
        return x.ToString(CultureInfo.InvariantCulture);
    }

    private static double DoubleFromString(string x)
    {
        return double.Parse(x, CultureInfo.InvariantCulture);
    }

    static Program()
    {
        //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        consoleReader = new StreamReader(Console.OpenStandardInput(BufferSize), Encoding.ASCII, false, BufferSize);
    }

    private static void PushTestData(StringBuilder sb)
    {
        PushTestData(sb.ToString());
    }
    private static void PushTestData(string data)
    {
#if TOLYAN_TEST
        if (testData == null)
        {
            testData = new MemoryStream();
            consoleReader = new StreamReader(testData);
        }

        var pos = testData.Position;
        var bytes = Encoding.UTF8.GetBytes(data);
        testData.Write(bytes, 0, bytes.Length);
        testData.Flush();
        testData.Position = pos;
#endif
    }
    #endregion
}

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

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200\,000$$$, $$$2 \le k \le n$$$) — the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday. The second line contains the string with length $$$n$$$ consisting of zeros and ones. If the $$$i$$$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $$$i$$$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $$$i$$$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.

Print the minimum possible break in minutes between eating chocolate bars.

NoteIn the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.In the second example Polycarp will eat bars in the minutes $$$1$$$ and $$$8$$$ anyway, also he needs to eat the chocolate bar in the minute $$$5$$$, so that the time of the maximum break will be equal to $$$3$$$ minutes.

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

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

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

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

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

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


using System;
using System.Collections.Generic;

namespace Task2
{
    class Program
    {
        private struct Spell
        {
            public int N;
            public int pow;
            public int dmg;

            public static Spell NullSpell
            {
                get { return new Spell() {N = -1, dmg = -1, pow = -1}; }
            }
        }

        private struct Cast
        {

            public int time;
            public int spell;
        }

        static void Main(string[] args)
        {
            string line;

            line = Console.ReadLine();
            string[] arg1 = line.Split();

            int N = int.Parse(arg1[0]);
            int max = int.Parse(arg1[1]);
            int reg = int.Parse(arg1[2]);

            List<Spell> spells = new List<Spell>();

            for (int i = 0; i < N; i++)
            {
                line = Console.ReadLine();
                string[] arg2 = line.Split();

                int pow = int.Parse(arg2[0]);
                int dmg = int.Parse(arg2[1]);

                spells.Add(new Spell() {N = i + 1, pow = pow, dmg = dmg});
            }

            spells.Sort( (x, y) => y.dmg.CompareTo(x.dmg)); //sort desc

            List<Cast> usedSpells = new List<Cast>();

            int currentDmg = 0;
            int currentHp = max;
            int currentTime = 0;

            do
            {
                currentHp -= currentDmg;

                currentHp += reg;
                if (currentHp > max)
                    currentHp = max;

                Spell spell = GetBestSpell(currentHp, max, spells);
                if (spell.Equals(Spell.NullSpell))
                {
                    if (reg >= currentDmg && currentHp > 0)
                    {
                        OutNoSolution();
                        return;
                    }
                }
                else
                {
                    currentDmg += spell.dmg;
                    spells.Remove(spell);

                    usedSpells.Add(new Cast() {spell = spell.N, time = currentTime});
                }

                if (currentHp <= 0)
                {
                    OutSolution(usedSpells, currentTime);
                    return;
                }

                currentTime++;
            } while (true);
        }

        private static void OutNoSolution()
        {
            Console.WriteLine("NO");

        }

        private static void OutSolution(List<Cast> usedSpells, int time)
        {
            Console.WriteLine("YES");
            Console.WriteLine("{0} {1}", time, usedSpells.Count);

            foreach (var cast in usedSpells)
            {
                Console.WriteLine("{0} {1}", cast.time, cast.spell);
            }
        }

        private static Spell GetBestSpell(int currentHp, int max, List<Spell> spells)
        {
            for (int i = 0; i < spells.Count; i++)
                if ((long)currentHp * 100 <= (long)spells[i].pow * max)
                {
                    return spells[i];
                }

            return Spell.NullSpell;
        }
    }
}

Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive ( ≤ 0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.

The first line contains three integers N, max and reg (1 ≤ N, max, reg ≤ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0 ≤ powi ≤ 100, 1 ≤ dmgi ≤ 2000).

In case Petya can’t complete this level, output in the single line NO. Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds. Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.

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

class Program
{

    void solve()
    {
        int n = nextInt();
        int max = nextInt();
        int reg = nextInt();
        int[] p = new int[n];
        int[] dam = new int[n];
        for (int i = 0; i < n; i++)
        {
            p[i] = nextInt();
            dam[i] = nextInt();
        }
        int t = 0;
        int[] who = new int[2002];
        for (int i = 0; i < who.Length; i++)
            who[i] = -1;
        bool[] used = new bool[n];
        int v = max;
        while (true)
        {
            if (t >= 40000)
                break;
            for (int i = 0; i < n; i++)
            {
                if (used[i])
                {
                    v -= dam[i];
                }
            }
            v += reg;
            if (v >= max)
                v = max;
            if (v <= 0)
                break;
            int z = -1;
            int best = -1;
            for (int i = 0; i < n; i++)
            {
                if (used[i])
                    continue;
                if (v * 100 <= p[i] * max)
                {
                    if (best < dam[i])
                    {
                        best = dam[i];
                        z = i;
                    }
                }
            }
            if (z != -1)
            {
                used[z] = true;
                who[t] = z;
            }
            t++;
        }
        if (v <= 0)
        {
            println("YES");
            int cnt = 0;
            for (int i = 0; i < n; i++)
                if (used[i])
                    cnt++;
            println(t+" "+cnt);
            for(int i=0;i<who.Length;i++)
                if (who[i] != -1)
                {
                    println(i + " " + (who[i] + 1));
                }

        }
        else
        {
            println("NO");
        }

    }

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

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

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

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

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


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

class Myon
{
    public Myon() { }
    public static int Main()
    {
        new Myon().calc();
        return 0;
    }

    Scanner cin;

    void calc()
    {
        cin = new Scanner();
        int N = cin.nextInt();
        long[] A = new long[N];
        int count1 = 0;
        for (int i = 0; i < N; i++)
        {
            A[i] = cin.nextLong();
            if (A[i] == 1) count1++;
        }
        Array.Sort(A);

        int MAX = 200000;

        int ok = MAX;
        int ng = 0;

        long[] NGar = new long[N];
        long[] OKar = new long[N];
        int NGcnt, OKcnt;

        while(ok - ng > 1)
        {
            int mid = (ok + ng) / 2;
            long p2Num = 0;
            int p2 = mid;

            long preNum = 1;
            int pre = 0;
            bool flag = true;
            NGcnt = OKcnt = 0;

            foreach (var now in A)
            {
                while(now > preNum)
                {
                    if (p2Num != 0)
                    {
                        for (int i = 0; i < p2; i++)
                        {
                            OKar[OKcnt++] = p2Num;
                        }
                    }
                    p2 = pre;
                    p2Num = preNum;
                    pre = 0;
                    preNum *= 2;
                }
                if(p2 >= 1 && now == preNum)
                {
                    pre++;
                    p2--;
                }
                else
                {
                    NGar[NGcnt++] = now;
                }

            }

            for (int i = 0; i < p2; i++)
            {
                OKar[OKcnt++] = p2Num;
            }
            for (int i = 0; i < pre; i++)
            {
                OKar[OKcnt++] = preNum;
            }

            int o = 0;
            int nn = 0;
            while(o < OKcnt && nn < NGcnt)
            {
                if (OKar[o] * 2 >= NGar[nn]) nn++;
                o++;
            }

            if (nn < NGcnt) flag = false;

            if (flag) ok = mid;
            else  ng = mid;
        }

        if (ok == MAX) Console.WriteLine(-1);
        else
        {
            for (int i = ok; i <= count1; i++)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
        }
    }
}

class Scanner
{
    string[] s;
    int i;

    char[] cs = new char[] { ' ' };

    public Scanner()
    {
        s = new string[0];
        i = 0;
    }

    public string next()
    {
        if (i < s.Length) return s[i++];
        string st = Console.ReadLine();
        while (st == "") st = Console.ReadLine();
        s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
        i = 0;
        return s[i++];
    }

    public int nextInt()
    {
        return int.Parse(next());
    }

    public long nextLong()
    {
        return long.Parse(next());
    }

    public double nextDouble()
    {
        return double.Parse(next());
    }

}

It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k ≥ 0, 0 <; r ≤ 2k. Let's call that representation prairie partition of x.For example, the prairie partitions of 12, 17, 7 and 1 are:  12 = 1 + 2 + 4 + 5,17 = 1 + 2 + 4 + 8 + 2,7 = 1 + 2 + 4,1 = 1. Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of numbers given from Alice to Borys. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1012; a1 ≤ a2 ≤ ... ≤ an) — the numbers given from Alice to Borys.

Output, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input. If there are no such values of m, output a single integer -1.

NoteIn the first example, Alice could get the input sequence from [6, 20] as the original sequence.In the second example, Alice's original sequence could be either [4, 5] or [3, 3, 3].

namespace ZT.Contests.Codeforces
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    internal static class Program
    {
        public static void Main(string[] args)
        {
            var solver = new PrairiePartition();
            var input = new TextInputHelper(Console.In);
            solver.DoWork(input);
        }
    }

    internal class PrairiePartition : CFSolver
    {
        // 2^(ValueU2-1) should be larger than the largest value
        private const int ValueU2 = 42;

        public PrairiePartition(RunType runType = RunType.ReadUntilNoInput) : base(runType) { }

        public override void Solve(InputHelper input)
        {
            var n = input.Read<int>();
            var a = new long[n];
            for (var i = 0; i < n; ++i) a[i] = input.Read<long>();

            var sum = new int[ValueU2]; // count of number no less than 2^j
            var b = new int[ValueU2]; // count of number equal to 2^j
            for (int j = ValueU2 - 1, i = n - 1; j >= 0; --j)
            {
                var c = 1L << j;
                for (; i >= 0 && a[i] > c; --i) ;
                sum[j] = n - i - 1;
                var qi = i;
                for (; i >= 0 && a[i] >= c; --i) ;
                b[j] = qi - i;
            }
            //Console.WriteLine($"sum: {string.Join(" ", sum)}\nb: {string.Join(" ", b)}");
            var res = new List<int>();
            for (var r = (b[0] + 1) / 2; r <= b[0]; ++r)
            {
                var u = new int[ValueU2];
                var v = new int[ValueU2];
                //Console.WriteLine($"check {r}");
                Func<int, int, bool> cal = null;
                cal = (j, c) =>
                {
                    if (j == ValueU2 - 1) return true; // 2^(ValueU2-1) is larger than the largest element
                    u[j] = Math.Min(c, b[j]);
                    if (!cal(j + 1, u[j])) return false;
                    var d = sum[j] - sum[j + 1] - u[j + 1];
                    v[j] = v[j + 1] + d;
                    //Console.WriteLine($"\t{j}: {u[j]} {v[j]} ({d})");
                    return u[j] >= v[j];
                };
                if (cal(0, r) && u[0] - v[0] >= b[0] - u[0]) res.Add(r);
            }
            Console.WriteLine(res.Any() ? string.Join(" ", res) : "-1");
        }
    }

    internal abstract class CFSolver
    {
        public const long Mod = 1000000007;

        public CFSolver(RunType runType)
        {
            RunType = runType;
        }

        public RunType RunType { get; private set; }

        public void DoWork(InputHelper input)
        {
            Func<bool> shouldRun;

            switch (RunType)
            {
                case RunType.ReadRunTimeFromInput:
                    shouldRun = GetShouldRun(input.Read<int>());
                    break;
                case RunType.ReadUntilNoInput:
                    shouldRun = () => input.HasNext();
                    break;
                default:
                    shouldRun = GetShouldRun(1);
                    break;
            }

            while (shouldRun())
            {
                Solve(input);
            }
        }

        public abstract void Solve(InputHelper input);

        private static Func<bool> GetShouldRun(int n) { return () => n-- > 0; }
    }

    public enum RunType
    {
        Single,
        ReadRunTimeFromInput,
        ReadUntilNoInput,
    }

    public abstract class InputHelper
    {
        private bool any;
        private IEnumerator<string> cur;

        public T Read<T>()
        {
            if (!HasNext()) { throw new InvalidOperationException("no more data"); }
            var r = (T)Convert.ChangeType(cur.Current, typeof(T));
            any = false;
            return r;
        }

        public bool HasNext()
        {
            while (!any)
            {
                if (cur != null && cur.MoveNext()) break;
                var next = GetNextGroup();
                if (next == null) { return false; }
                cur = next.GetEnumerator();
                any = cur.MoveNext();
            }

            return any = true;
        }

        protected abstract IEnumerable<string> GetNextGroup();
    }

    public class TextInputHelper : InputHelper
    {
        private TextReader reader;

        public TextInputHelper(TextReader reader) { this.reader = reader; }

        protected override IEnumerable<string> GetNextGroup()
        {
            if (reader == null) { return null; }
            var cur = reader;
            reader = null;
            return ReadWordsToEnd(cur);
        }

        public static IEnumerable<string> ReadWordsToEnd(TextReader reader)
        {
            while (true)
            {
                var lines = ReadWords(reader);
                if (lines == null) yield break;
                foreach (string word in lines) yield return word;
            }
        }

        public static IEnumerable<string> ReadWords(TextReader reader)
        {
            string line = reader.ReadLine();
            return line == null ? null : line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
        }
    }
}


require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

gets
front = gets.split.map &:to_i
gets
back = gets.split.map &:to_i

hash = Hash.new( 0 )

front_x.each{|v1|
  back_x.each{|v2|
    next if v1 % v2 != 0

    hash[back_x / front_x]+=1
  }
}

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

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

gets
a = gets.split.map &:to_i
gets
b = gets.split.map &:to_i

c = b.product(a).map{ |bi,aj| bi*1.0/aj }.select{ |i| i%1 == 0 }
puts c.count c.max


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

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


def ga = gets.split.map!(&:to_i)
def gi = gets.to_i
def giga = [gi, ga]
def gigs = [gi, gs]
def gs = gets.strip
def gss = gs.split
def o(x) = puts(x)
def pa(a, d = ' ') = puts(a * d)
def pan(a) = pa(a, "\n")
def yn(p) = p ? 'YES' : 'NO'
def ync(p) = p ? 'Yes' : 'No'
def hz(d = 0) = Hash.new(d)
def rqr(*a) = a.each { require _1 }
class Set def z = size end
class Array
    def r! = reverse!
    def f = first
    def l = last
    def sh = shift
    def j(...) = join(...)
    def pc = pack('c*')
    def psum!(s = 0) = map! { s += _1 }
    def lbound(x) = bsearch { _1 >= x }
    def lbound_index(x) = bsearch_index { _1 >= x }
    def hoare!(...) = shuffle!.sort!(...)
    def z = size
end
module Enumerable
    def e(...) = each(...)
    def ei(...) = each_index(...)
    def re(...) = reverse_each(...)
    def ec(...) = each_cons(...)
    def es(...) = each_slice(...)
    def wo(...) = with_object(...)
    def wi(...) = with_index(...)
    def ewi(...) = each_with_index(...)
    def ewo(...) = each_with_object(...)
    def fold(...) = reduce(...)
end
class String
    def i(...) = to_i(...)
    def e(...) = each_char(...)
    def eb(...) = each_byte(...)
    def b = bytes
    def r = reverse
    def z = size
end
class Numeric
    def f = to_f
    def i = to_i
    def s(...) = to_s(...)
    def sqrt = Math.sqrt(self)
    def isqrt = Integer.sqrt(self)
end
class Integer
    def p = pred
    def n = succ
    def t(...) = times(...)
    def popcount = loop.reduce((raise if (x = self) < 0; 0)) \
        { | r | break r if x < 1; r += x & 1; x >>= 1; r }
    def ctz = loop.reduce((raise if (x = self) <= 0; 0)) \
        { | r | break r if x[0] == 1; x >>= 1; r.n }
end
class Hash
    def ek(...) = each_key(...)
    def ev(...) = each_value(...)
    def kmin = ek.min
    def kmax = ek.max
    def vmin = ev.min
    def vmax = ev.max
    def d(...) = delete(...)
    def z = size
end
class MSet < Hash
    def <<(x) = (self[x] = (self[x] || 0).n; self)
    def d(x) = (self.delete x if (self[x] && self[x] -= 1) == 0)
end
def fio(a = 'input.txt', b = 'output.txt')
    $stdin = File.open a, 'rb'
    $stdout = File.open b, 'wb'
end
rqr 'set', 'prime'
class Set def d(...) = delete(...) end
class Prime
    def self.at_least(x) =
        loop { Prime.prime?(x) ? (break x) : x += 1 }
end
RC = /(.)\1*/

################################################################
#                                                              #
#              https://github.com/alantudyk/Stop               #
#                                                              #
################################################################

o ('abcd' + ?a * 1e5)[...gi]

################################################################
#                                                              #
#              https://github.com/alantudyk/Stop               #
#                                                              #
################################################################

Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3,10 d: 4,8 e: 6 f: 7 z: 1,5,9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5-1=4, 9-5=4, for letters c: 10-3=7, for letters d: 8-4=4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.

The single line contains a positive integer n (1≤n≤10^5) — the length of the sought string.

Print on the single line the lexicographically minimal lucky string whose length equals n.

The lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1≤i≤n), that ai<bi, and for any j (1≤j<i) aj=bj.

def ga = gets.split.map!(&:to_i)
def gi = gets.to_i
def giga = [gi, ga]
def gigs = [gi, gs]
def gs = gets.strip
def gss = gs.split
def o(x) = puts(x)
def pa(a, d = ' ') = puts(a * d)
def pan(a) = pa(a, "\n")
def yn(p) = p ? 'YES' : 'NO'
def ync(p) = p ? 'Yes' : 'No'
def hz(d = 0) = Hash.new(d)
def rqr(*a) = a.each { require _1 }
class Set def z = size end
class Array
    def r! = reverse!
    def f = first
    def l = last
    def sh = shift
    def j(...) = join(...)
    def pc = pack('c*')
    def psum!(s = 0) = map! { s += _1 }
    def lbound(x) = bsearch { _1 >= x }
    def lbound_index(x) = bsearch_index { _1 >= x }
    def hoare!(...) = shuffle!.sort!(...)
    def z = size
end
module Enumerable
    def e(...) = each(...)
    def ei(...) = each_index(...)
    def re(...) = reverse_each(...)
    def ec(...) = each_cons(...)
    def es(...) = each_slice(...)
    def wo(...) = with_object(...)
    def wi(...) = with_index(...)
    def ewi(...) = each_with_index(...)
    def ewo(...) = each_with_object(...)
    def fold(...) = reduce(...)
end
class String
    def i(...) = to_i(...)
    def e(...) = each_char(...)
    def eb(...) = each_byte(...)
    def b = bytes
    def r = reverse
    def z = size
end
class Numeric
    def f = to_f
    def i = to_i
    def s(...) = to_s(...)
    def sqrt = Math.sqrt(self)
    def isqrt = Integer.sqrt(self)
end
class Integer
    def p = pred
    def n = succ
    def t(...) = times(...)
    def popcount = loop.reduce((raise if (x = self) < 0; 0)) \
        { | r | break r if x < 1; r += x & 1; x >>= 1; r }
    def ctz = loop.reduce((raise if (x = self) <= 0; 0)) \
        { | r | break r if x[0] == 1; x >>= 1; r.n }
end
class Hash
    def ek(...) = each_key(...)
    def ev(...) = each_value(...)
    def kmin = ek.min
    def kmax = ek.max
    def vmin = ev.min
    def vmax = ev.max
    def d(...) = delete(...)
    def z = size
end
class MSet < Hash
    def <<(x) = (self[x] = (self[x] || 0).n; self)
    def d(x) = (self.delete x if (self[x] && self[x] -= 1) == 0)
end
def fio(a = 'input.txt', b = 'output.txt')
    $stdin = File.open a, 'rb'
    $stdout = File.open b, 'wb'
end
rqr 'set', 'prime'
class Set def d(...) = delete(...) end
class Prime
    def self.at_least(x) =
        loop { Prime.prime?(x) ? (break x) : x += 1 }
end
RC = /(.)\1*/

################################################################
#                                                              #
#              https://github.com/alantudyk/Stop               #
#                                                              #
################################################################

o ('abcd' * 25e3)[...gi]

################################################################
#                                                              #
#              https://github.com/alantudyk/Stop               #
#                                                              #
################################################################

[{'input': ['5\r\n'], 'output': ['abcda\r\n']}, {'input': ['3\r\n'], 'output': ['abc\r\n']}, {'input': ['8\r\n'], 'output': ['abcdabcd\r\n']}, {'input': ['10\r\n'], 'output': ['abcdabcdab\r\n']}, {'input': ['16\r\n'], 'output': ['abcdabcdabcdabcd\r\n']}, {'input': ['64\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd\r\n']}, {'input': ['128\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd\r\n']}, {'input': ['100\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd\r\n']}, {'input': ['47\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabc\r\n']}, {'input': ['74\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdab\r\n']}, {'input': ['477\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcda\r\n']}, {'input': ['1\r\n'], 'output': ['a\r\n']}, {'input': ['2\r\n'], 'output': ['ab\r\n']}, {'input': ['7\r\n'], 'output': ['abcdabc\r\n']}, {'input': ['4\r\n'], 'output': ['abcd\r\n']}, {'input': ['99\r\n'], 'output': ['abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabc\r\n']}, {'input': ['6\r\n'], 'output': ['abcdab\r\n']}, {'input': ['9\r\n'], 'output': ['abcdabcda\r\n']}]


n, vb, vs = gets.split.map{|i| i.to_f}
x = gets.split.map{|i| i.to_i}
xu, yu = gets.split.map{|i| i.to_i}
ans = [1e100, -1, -1]
1.upto(x.length - 1) do |i|
	d = (xu - x[i]) ** 2 + yu ** 2
	t = x[i] / vb + Math.sqrt(d) / vs
	ans = [d, t, i] if t < ans[0] - 1e-8 || (t < ans[0] + 1e-8 && d < ans[1])
end
p ans[2] + 1

And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mint = 0
mind = 0
idx = 0
for i in 1..n-1
	wk = (ar[i]-xu).abs
	wkt = ar[i].to_f/vb+Math.sqrt(wk*wk + yu*yu)/vs
	if idx == 0 || mint > wkt
		mint = wkt
		mind = wk
		idx = i+1
	elsif mint == wkt
		if mind > wk
			mint = wkt
			mind = wk
			idx = i+1
		end
	end
end
puts idx


gets
bats = gets.split.map &:to_i
prizes = gets.split.map &:to_i
score = 0
res = prizes.map{0}
for bat in bats
    score += bat

    can = prizes.select{ |prize| prize <= score }
    break if can.empty?
    res[prizes.index(can.max)] += score / can.max
    score %= can.max

end
puts res.join " "
puts score

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

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

def koukan()
    return -1 if $sum < $aa[0]
    5.downto(1) { |i|
        return i-1 if $aa[i-1] <= $sum
    }
end

$n = gets.chomp.to_i
$sa = gets.chomp.split(/ /).map!{|x| x.to_i}
$aa = gets.chomp.split(/ /).map!{|x| x.to_i}
$sum = 0
$suma = Array.new(5).map!{|x| x = 0}
for i in 0..$n-1
    $sum += $sa[i]
    while (true)
        if $sum > $aa[4]
            wka = $sum.divmod($aa[4])
            $suma[4] += wka[0]
            $sum -= $aa[4] * wka[0]
        end
        ret = koukan()
        break if ret < 0
        $suma[ret] += 1
        $sum -= $aa[ret]
    end
end
puts $suma.join(" ")
puts $sum


k=gets.split[1].to_i
a=gets.split.map(&:to_i)

ranks=Array.new(104,0)
a.each{|i| ranks[i]+=1}
ans=0
n=a.length
loop do
        if ranks[k]==n then
                puts ans
                exit
        end
        next_rank=Array.new(104,0)
        1.upto(k-1){|a|
                next_rank[a]+=ranks[a]/2
                next_rank[a+1]+=(ranks[a]+1)/2
        }
        next_rank[k]+=ranks[k]
        ranks=next_rank
        ans+=1
end

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

The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.

k=gets.split[1].to_i
a=gets.split.map(&:to_i)

ranks=Array.new(104,0)
a.each{|i| ranks[i]+=1}
ans=0
n=a.length
loop do
        if ranks[k]==n then
                puts ans
                exit
        end
        next_rank=Array.new(104,0)
        1.upto(k-1){|a|
                next_rank[a]+=[ranks[a]-1,0].max
                next_rank[a+1]+=[ranks[a],1].min
        }
        next_rank[k]+=ranks[k]
        ranks=next_rank
        ans+=1
end


$n,$m=gets.split.map &:to_i
$e=Array.new($n+1){[]}
$m.times{a,b=gets.split.map &:to_i;$e[a]<<b;$e[b]<<a}
$visited=[]
def dfs(pos)
	$visited<<pos
	($e[pos]-$visited).each{|_pos|return true if dfs(_pos)}
	return $visited.size==$n ? true : false
end
puts $n>2&&$n==$m&&dfs(1) ? "FHTAGN!" : "NO"

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

The first line contains two integers — the number of vertices n and the number of edges m of the graph (1 ≤ n ≤ 100, 0 ≤ m ≤ ). Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 ≤ x, y ≤ n, x ≠ y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.

Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.

NoteLet us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).A rooted tree is a tree where one vertex is selected to be the root.

n,m = gets.split(' ').map(&:to_i)

sm = [];
n.times do |i| sm[i] = [] end

m.times do
    a,b = gets.split(' ').map(&:to_i)
    a -= 1
    b -= 1
    sm[a][b] = 1
end

p = []
$q = 0
def rec(id,p,sm,n)
    p[id] |= 0
    if p[id] == 1 then return end
    p[id] = 1
    $q += 1
    n.times do |i|
        sm[id][i] |= 0
        if sm[id][i] == 1 or sm[i][id] == 1 then
            rec(i,p,sm,n)
        end
    end
end

rec(0,p,sm,n)
if($q == n and $q == m) then puts('FHTAGN!');
else puts('NO');
end


#!/usr/bin/ruby
gets
s=gets.chomp
loop{
	t=s.dup
	t.size.times{|i|
		r=0<i&&s[i-1,1]=='R'
		l=i<t.size-1&&s[i+1,1]=='L'
		if r^l
			t[i,1] = r ? 'R' : 'L'
		end
	}
	break if s==t
	s=t
}
p s.scan('.').count

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

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

#!/usr/bin/ruby
gets
s=gets.chomp
loop{
	t=s.dup
	t.size.times{|i|
		next if t[i,1]!='.'
		r=0<i&&s[i-1,1]=='R'
		l=i<t.size-1&&s[i+1,1]=='L'
		if r^l
			t[i,1] = r ? 'R' : 'L'
		end
	}
	break if s==t
	s=t
}
p s.scan('.').count


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

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

n=gets.to_i
a=[nil,]
m=1
a+=gets.split.map{|v| v.to_i}

for i in 1..n do
  c=1
  (i+1..n).each do |j|
	if a[j]<=a[j-1] then c+=1
	else break
	end
  end

  (1..i-1).reverse_each do |j|
    if a[j]<=a[j+1] then c+=1
	else break
	end
  end

  if c>m then num=i; m=c; end
end

puts m


s2 = (gets.to_i+1)/2
a = gets(p).scan(/(\S+) (\S+)/)
af,al = a.transpose

as = a.flatten.sort.each_slice(a.size/2).map(&:first)
x = as.select{ |i|
    a.count{ |j,k| j == i || k == i } >= s2
}

p x.empty? ? -1 : [(
    a1 = af.group_by{|i|i}
    s2 - x.map{ |i| a1[i] ? a1[i].size : 0 }.max
    #s2 - x.map{ |i| af.count i }.max
), 0].max

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

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces.

On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.

NoteIn the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.

s=(gets.to_i+1)/2
a=gets(p).scan /(\S+) (.+)/
x=a.flatten.sort.each_slice([a.size/2,1].max).map(&:first).select{|i|a.count{|j,k|j==i||k==i}>=s}
p x[0]?[s-x.map{|i|a.map(&:first).count i}.max,0].max: -1


k = gets.chomp.split(" ")
n = k[0].to_i
b = k[1].to_f
m = gets.chomp.split(" ")
sum = 0

for i in(0..n-1)
	m[i] = m[i].to_f
	sum += m[i]
end

for i in(0..n-1)
	if b/n < m[i] then
		puts -1
		break
	end

	m[i] = (b+sum)/n - m[i]
	puts m[i]
end

A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously:   there were b milliliters poured in total. That is, the bottle need to be emptied;  after the process is over, the volumes of the drink in the mugs should be equal.

The first line contains a pair of integers n, b (2 ≤ n ≤ 100, 1 ≤ b ≤ 100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the current volume of drink in the i-th mug.

Print a single number "-1" (without the quotes), if there is no solution. Otherwise, print n float numbers c1, c2, ..., cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique. Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.

n,b = gets.chomp.split(/ /).map!{|x| x.to_i}
a = gets.chomp.split(/ /).map!{|x| x.to_i}
ma = a.max
af = []
wk = 0
for i in 0..a.length-1
  af << (ma - a[i])
  wk += af[i]
end
if wk > b
  puts "-1"
else
  wkf = (b - wk).to_f / a.length
  for i in 0..af.length-1
    puts format("%.6f",(wkf+af[i]))
  end
end


require 'pry'
def read_ints; gets.chomp.split.map(&:to_i) end
n = read_ints[0]
current = 0
max = 0
current_stack = []
n.times do
	line = gets.chomp.split
	if(line[0]=='+')
		#new man come
		current+=1
		current_stack<<line[1].to_i
		max = current if current>max
	else
		#man come out
		man_id = line[1].to_i
		if(current_stack.include? man_id)
			current_stack.delete(man_id)
			current-=1
		else #was there from begging
			max+=1
		end
	end
end
puts max

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

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

#!/usr/bin/ruby
h={}
cap=cur=0
gets.to_i.times{
	x,y=gets.split
	y=y.to_i
	if x=='+' && !h[y]
		cur+=1
		h[y]=1
	elsif x=='-' && h[y]
		cur-=1
		h[y]=nil
	elsif x=='-' && !h[y]
		cap+=1
	end
	cap=[cap,cur].max
}
p cap


Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.

The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.

Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.


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

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.