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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    string[] a = { "Ac","Ag","Al","Am","Ar","As","At","Au","B","Ba","Be","Bh","Bi","Bk","Br","C","Ca","Cd","Ce","Cf","Cl","Cm","Cn","Co","Cr","Cs","Cu","Db","Ds","Dy","Er","Es","Eu","F","Fe","Fl","Fm","Fr","Ga","Gd","Ge","H","He","Hf","Hg","Ho","Hs","I","In","Ir","K","Kr","La","Li","Lr","Lu","Lv","Mc","Md","Mg","Mn","Mo","Mt","N","Na","Nb","Nd","Ne","Nh","Ni","No","Np","O","Og","Os","P","Pa","Pb","Pd","Pm","Po","Pr","Pt","Pu","Ra","Rb","Re","Rf","Rg","Rh","Rn","Ru","S","Sb","Sc","Se","Sg","Si","Sm","Sn","Sr","Ta","Tb","Tc","Te","Th","Ti","Tl","Tm","Ts","U","V","W","Xe","Y","Yb","Zn","Zr"};
    Dictionary<char, List<string>> d;

    bool Fun(int p, string s)
    {
        if (p >= s.Length)
            return true;
        foreach (string v in d[s[p]])
            if (p + v.Length <= s.Length && s.Substring(p, v.Length) == v && Fun(p + v.Length, s))
                return true;
        return false;
    }

    public void Solve()
    {
        d = new Dictionary<char, List<string>>();
        for (char i = 'A'; i <= 'Z'; i++)
            d[i] = new List<string>();
        foreach (string aa in a)
        {
            d[aa[0]].Add(aa.ToUpper());
        }

        string s = ReadToken();
        Write(Fun(0, s) ? "YES" : "NO");
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        //reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("input.txt");
        //writer = new StreamWriter("output.txt");
#endif
        try
        {
            new Solver().Solve();
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine(ex);
#else
            throw;
#endif
        }
        reader.Close();
        writer.Close();
    }

    #endregion

    #region Read / Write
    private static Queue<string> currentLineTokens = new Queue<string>();
    private static string[] ReadAndSplitLine() { return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries); }
    public static string ReadToken() { while (currentLineTokens.Count == 0)currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue(); }
    public static int ReadInt() { return int.Parse(ReadToken()); }
    public static long ReadLong() { return long.Parse(ReadToken()); }
    public static double ReadDouble() { return double.Parse(ReadToken(), CultureInfo.InvariantCulture); }
    public static int[] ReadIntArray() { return ReadAndSplitLine().Select(int.Parse).ToArray(); }
    public static long[] ReadLongArray() { return ReadAndSplitLine().Select(long.Parse).ToArray(); }
    public static double[] ReadDoubleArray() { return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); }
    public static int[][] ReadIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++)matrix[i] = ReadIntArray(); return matrix; }
    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++)ret[i][j] = matrix[j][i]; } return ret;
    }
    public static string[] ReadLines(int quantity) { string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++)lines[i] = reader.ReadLine().Trim(); return lines; }
    public static void WriteArray<T>(IEnumerable<T> array) { writer.WriteLine(string.Join(" ", array)); }
    public static void Write(params object[] array) { WriteArray(array); }
    public static void WriteLines<T>(IEnumerable<T> array) { foreach (var a in array)writer.WriteLine(a); }
    private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        public new TValue this[TKey key]
        {
            get { return ContainsKey(key) ? base[key] : default(TValue); }
            set { base[key] = value; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}


using System;
using System.Linq;

namespace Browsers
{
    class Program
    {
        static void Main(string[] args)
        {
            var numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var types = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var n = numbers[0];
            var k = numbers[1];

            Console.WriteLine(Score(types, k));
        }

        private static int Score(int[] cites, int k)
        {
            var highest = 0;
            for (var i = 0; i < cites.Length; i++)
            {
                var score = 0;
                for (var j = 0; j < cites.Length; j++)
                {
                    if ((j - i) % k == 0) continue;
                    score += cites[j];
                }

                if (Math.Abs(score) > highest)
                {
                    highest = Math.Abs(score);
                }
            }

            return highest;
        }
    }
}


// Problem: 1100A - Roman and Browser
// Author: Gusztav Szmolik

using System;

class RomanAndBrowser
    {
    static int Main ()
        {
        string[] words = ReadSplitLine (2);
        if (words == null)
            return -1;
        byte n;
        if (!Byte.TryParse (words[0], out n))
            return -1;
        if (n < 3 || n > 100)
            return -1;
        byte k;
        if (!Byte.TryParse (words[1], out k))
            return -1;
        if (k < 2 || k >= n)
            return -1;
        words = ReadSplitLine (n);
        if (words == null)
            return -1;
        sbyte[] tabTypes = new sbyte[n];
        for (byte i = 0; i < n; i++)
            {
            sbyte tti;
            if (!SByte.TryParse (words[i], out tti))
                return -1;
            if (tti != -1 && tti != 1)
                return -1;
            tabTypes[i] = tti;
            }
        byte ans = 0;
        for (byte i = 0; i < n; i++)
            {
            sbyte sum = 0;
            byte r = Convert.ToByte (i%k);
            for (byte j = 0; j < n; j++)
                if (j%k != r)
                    sum += tabTypes[j];
            if (sum < 0)
                sum *= -1;
            if (sum > ans)
                ans = (byte)sum;
            }
        Console.WriteLine (ans);
        return 0;
        }

    static string[] ReadSplitLine (uint numWordNeed)
        {
        string line = Console.ReadLine ();
        if (line == null)
            return null;
        char[] delims = new char[2] {' ', '\t'};
        string[] words = line.Split (delims,StringSplitOptions.RemoveEmptyEntries);
        return (words.Length == numWordNeed ? words : null);
        }
    }


using System;
using System.Collections.Generic;

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++];
        s = Console.ReadLine().Split(cs, StringSplitOptions.RemoveEmptyEntries);
        i = 0;
        return s[i++];
    }

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

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

}

class Myon
{
    Scanner cin;
    Random r;
    Myon() { }

    public static void Main()
    {
        new Myon().calc();
    }

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

    int[,] dp;

    void calc()
    {
        cin = new Scanner();
        int n = cin.nextInt();
        int m = cin.nextInt();
        dp = new int[n + 1, m + 1];
        Console.WriteLine(saiki(n, m));
    }

    int saiki(int a, int b)
    {
        if (a == 0 && b == 0) return a;
        if (dp[a, b] != 0) return dp[a, b];
        int reta = (a / 4) * 2 + Math.Min(a % 4, 2);
        int retb = (b / 4) * 2 + Math.Min(b % 4, 2);
        int ret = reta * retb;
        ret = Math.Max((a + 2) / 3 * b, ret);
        ret = Math.Max((b + 2) / 3 * a, ret);
        if (a > 3) ret = Math.Max(ret, saiki(a - 3, b) + b);
        if (b > 3) ret = Math.Max(ret, saiki(a, b - 3) + a);
        ret = Math.Max(ret, (a * b + 1) / 2);
        return dp[a, b] = ret;
    }
}


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

public class taskB
{
    public class MyReader
    {
        private TextReader instream;

        public int[] ReadIntArray()
        {
            string inp = instream.ReadLine().Trim();
            string[] spl = inp.Split(' ');

            int[] a = new int[spl.Length];
            for (int i = 0; i < a.Length; i++)
                a[i] = int.Parse(spl[i]);
            return a;
        }

        public long[] ReadLongArray()
        {
            string inp = instream.ReadLine().Trim();
            string[] spl = inp.Split(' ');

            long[] a = new long[spl.Length];
            for (int i = 0; i < a.Length; i++)
                a[i] = long.Parse(spl[i]);
            return a;
        }

        public double[] ReadDoubleArray()
        {
            string inp = instream.ReadLine().Trim();
            string[] spl = inp.Split(' ');

            double[] a = new double[spl.Length];

            System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
            nfi.NumberDecimalSeparator = ".";
            for (int i = 0; i < a.Length; i++)
                a[i] = double.Parse(spl[i], nfi);
            return a;
        }

        public int ReadInt()
        {
            return int.Parse(instream.ReadLine());
        }

        public long ReadLong()
        {
            return long.Parse(instream.ReadLine());
        }

        public void SetInStream(TextReader textReader)
        {
            this.instream = textReader;
        }

        internal string ReadLine()
        {
            return instream.ReadLine();
        }
    }

    static void Main(string[] args)
    {
        MyReader instream = new MyReader();
        instream.SetInStream(Console.In);

        TextWriter outstream = Console.Out;

        solve(instream, outstream);

    }

    private static void solve(MyReader instream, TextWriter outstream)
    {
        int[] ab = instream.ReadIntArray();

        int a = ab[0];
        int b = ab[1];

        if (a > b)
        {
            int t = a;
            a = b;
            b = t;
        }

        int r1 = a * ((b-1) / 3+1);
        int r2 = ((a-1) / 3 + 1) * b;

        int r3 = a * b / 2 + ((a * b) % 2 == 0 ? 0 : 1);

        int res = Math.Max(Math.Max(r1, r2), r3);

        if (a == 2)
        {
            if (b % 4 == 1)
            {
                res = b / 4 * 4 + 2;
            }
            else if (b % 4 == 2 || b % 4 == 3)
            {
                res = b / 4 * 4 + 4;
            }
        }
        outstream.WriteLine(res);
    }

}


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

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            long summ = MyConsoleInputStreamParser.GetLong, x = MyConsoleInputStreamParser.GetLong;
            var need = (summ - x) / 2;
            if (need < 0 || (summ - x) % 2 == 1)
                Console.WriteLine(0);
            else
            {
                var bits = new int[64];
                var temp = x;
                var count = 0;
                var nonZeroBits = 0;
                while (temp > 0)
                {
                    var bit = (int)(temp % 2);
                    bits[count] = bit;
                    count++;
                    temp /= 2;
                    nonZeroBits += bit == 1 ? 1 : 0;
                }
                if (nonZeroBits == 1 && need == 0)
                    Console.WriteLine(0);
                else if (need == 0)
                    Console.WriteLine((long)Math.Pow(2, nonZeroBits) - 2);
                else
                {
                    temp = need;
                    count = 0;
                    var fail = false;
                    while (temp > 0)
                    {
                        var bit = (int)(temp % 2);
                        if (bits[count] == 1 && bit == 1)
                        {
                            fail = true;
                            break;
                        }
                        count++;
                        temp /= 2;
                    }
                    if (fail)
                        Console.WriteLine(0);
                    else
                        Console.WriteLine((long)Math.Pow(2, nonZeroBits));
                }
            }
        }

        public static class MyConsoleInputStreamParser
        {
            private static TextReader reader = new StreamReader(Console.OpenStandardInput());
            private static Queue<string> currentLineStrings = new Queue<string>();

            public static string GetLine { get { return reader.ReadLine(); } }

            public static string GetString { get { while (currentLineStrings.Count == 0) currentLineStrings = new Queue<string>(GetStringArray); return currentLineStrings.Dequeue(); } }

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

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

            public static double GetDouble { get { return double.Parse(GetString, CultureInfo.InvariantCulture); } }

            public static char[] GetCharArray { get { return GetLine.ToCharArray(); } }

            public static string[] GetStringArray { get { return GetLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); } }

            public static int[] GetIntArray { get { return GetStringArray.Select(int.Parse).ToArray(); } }

            public static long[] GetLongArray { get { return GetStringArray.Select(long.Parse).ToArray(); } }

            public static double[] GetDoubleArray { get { return GetStringArray.Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); } }

            public static char[][] ReturnCharMatrix(int numberOfRows) { char[][] matrix = new char[numberOfRows][]; for (int i = 0; i < numberOfRows; i++) matrix[i] = GetCharArray; return matrix; }

            public static string[][] ReturnStringMatrix(int numberOfRows) { string[][] matrix = new string[numberOfRows][]; for (int i = 0; i < numberOfRows; i++) matrix[i] = GetStringArray; return matrix; }

            public static int[][] ReturnIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++) matrix[i] = GetIntArray; return matrix; }

            public static long[][] ReturnLongMatrix(int numberOfRows) { long[][] matrix = new long[numberOfRows][]; for (int i = 0; i < numberOfRows; i++) matrix[i] = GetLongArray; return matrix; }

            public static double[][] ReturnDoubleMatrix(int numberOfRows) { double[][] matrix = new double[numberOfRows][]; for (int i = 0; i < numberOfRows; i++) matrix[i] = GetDoubleArray; return matrix; }
        }
    }
}


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

namespace AlgoTraining.Codeforces._8VCVentureCup2016
{

    class FastScanner : StreamReader
    {
        private string[] _line;
        private int _iterator;

        public FastScanner(Stream stream) : base(stream)
        {
            _line = null;
            _iterator = 0;
        }
        public int NextInt()
        {
            if (_line == null || _iterator >= _line.Length)
            {
                _line = base.ReadLine().Split(' ');
                _iterator = 0;
            }
            if (_line.Count() == 0) throw new IndexOutOfRangeException("Input string is empty");
            return Convert.ToInt32(_line[_iterator++]);
        }
        public long NextLong()
        {
            if (_line == null || _iterator >= _line.Length)
            {
                _line = base.ReadLine().Split(' ');
                _iterator = 0;
            }
            if (_line.Count() == 0) throw new IndexOutOfRangeException("Input string is empty");
            return Convert.ToInt64(_line[_iterator++]);
        }
    }
    class XorEquationC
    {
        public static void Main(string[] args)
        {
            using (FastScanner fs = new FastScanner(new BufferedStream(Console.OpenStandardInput())))
            using (StreamWriter writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
            {
                long s = fs.NextLong(), x = fs.NextLong();
                if (s < x || (s - x) % 2 != 0)
                {
                    writer.WriteLine(0);
                    return;
                }
                long and = (s - x) / 2;
                string xorStr = Convert.ToString(x, 2), andStr = Convert.ToString(and, 2);
                int onesNum = 0;
                foreach (char c in xorStr)
                {
                    if (c == '1') onesNum++;
                }
                string shortStr = xorStr;
                string longStr = andStr;
                if (xorStr.Length > andStr.Length)
                {
                    shortStr = andStr;
                    longStr = xorStr;
                }
                int p = longStr.Length - 1;
                for (int i = shortStr.Length - 1; i >= 0; i--, p--)
                {
                    if (shortStr[i] == '1' && longStr[p] == '1')
                    {
                        writer.WriteLine(0);
                        return;
                    }
                }
                writer.WriteLine(Math.Pow(2, onesNum) - (and == 0 ? 2 : 0));
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using Pi = Pair<int, int>;

class Solver
{
    public Scanner sc;
    public void Solve()
    {
        int N, M;
        sc.Make(out N, out M);
        var A = sc.ArrInt;
        var L = Create(2, () => new HashSet<int>());
        for(int k = 0; k < 2; k++)
        {
            int[] a;
            if (k == 0) a = A.Take(N / 2).ToArray();
            else a = A.Skip(N / 2).ToArray();
            for(int j = 0; j < (1 << a.Length); j++)
            {
                var sum = 0;
                for (int l = 0; l < a.Length; l++)
                    if ((1 & j >> l) == 1) { sum += a[l]%M; if (sum >= M) sum -= M; }
                L[k].Add(sum);
            }
        }
        var dat = Create(2, id => {
            var r = new int[L[id].Count];
            var now = 0;
            foreach (var d in L[id]) r[now++] = d;
            Array.Sort(r);
            return r;
        });
        var max = 0;
        for(int i = 0; i < dat[0].Length; i++)
        {
            var l = LowerBound(dat[1], M - dat[0][i]);
            for(int k = -1; k < 2; k++)
            {
                int idx = (l + k + dat[1].Length) % dat[1].Length;
                chmax(ref max, (dat[1][idx] + dat[0][i]) % M);
            }
        }
        Console.WriteLine(max);
    }
     #region UpperBound/LowerBound
    public static int UpperBound<T>(IList<T> array, T value, Comparison<T> cmp = null)
    {
        cmp = cmp ?? Comparer<T>.Default.Compare;
        var low = -1;
        var high = array.Count;
        while (high - low > 1)
        {
            var mid = (high + low) / 2;
            if (cmp(array[mid], value) == 1) high = mid;
            else low = mid;
        }
        return high;
    }

    public static int LowerBound<T>(IList<T> array, T value, Comparison<T> cmp = null)
    {
        cmp = cmp ?? Comparer<T>.Default.Compare;
        var low = -1;
        var high = array.Count;
        while (high - low > 1)
        {
            var mid = (high + low) / 2;
            if (cmp(array[mid], value) != -1) high = mid;
            else low = mid;
        }
        return high;
    }
    #endregion
}

#region Template
public static class Template
{
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        var sol = new Solver() { sc = new Scanner() };
        //var th = new Thread(sol.Solve, 1 << 26);th.Start();th.Join();
        sol.Solve();
        Console.Out.Flush();
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid());
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static int MaxElement<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; }
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    public void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
    //public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    //public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    //public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}
public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString() => $"{v1.ToString()} {v2.ToString()}";
    public void Deconstruct(out T1 a, out T2 b) { a = v1; b = v2; }
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString() => $"{base.ToString()} {v3.ToString()}";
    public void Deconstruct(out T1 a, out T2 b, out T3 c) { Deconstruct(out a, out b); c = v3; }
}
#endregion


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

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

namespace ed32e
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        static void solution()
        {
            #region SOLUTION

            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var a = readIntArray();

            var fh = n / 2;
            if (n % 2 == 1)
            {
                fh++;
            }
            var sh = n / 2;

            var mv = 0;
            for (int i = 0; i < fh; i++)
            {
                mv |= 1 << i;
            }

            var arr = new long[mv + 1];
            for (int i = 0; i <= mv; i++)
            {
                arr[i] = sum(i, a, m, 0);
            }

            Array.Sort(arr);
            var max = arr[arr.Length - 1];

            var sm = 0;
            //for (int i = mv; i < n; i++)
            //{
            //    sm &= 1 << i;
            //}

            for (int i = 0; i < sh; i++)
            {
                sm |= 1 << i;
            }

            //var smin = mv + 1;
            var res = long.MinValue;
            for (int i = 0; i <= sm; i++)
            {
                var val = sum(i, a, m, fh);
                var nr = (val + max) % m;
                if (nr > res)
                {
                    res = nr;
                }

                var req = m - val - 1;
                //if (req <= 0)
                //{
                //    continue;
                //}

                var l = 0;
                var r = arr.Length - 1;
                while (true)
                {
                    if (l == r)
                    {
                        break;
                    }

                    var mid = l + (r - l + 1) / 2;
                    var vv = arr[mid];
                    if (vv <= req)
                    {
                        l = mid;
                    }
                    else
                    {
                        r = mid - 1;
                    }
                }

                if (arr[l] <= req)
                {
                    if (val + arr[l] > res)
                    {
                        res = val + arr[l];
                    }
                }
            }

            Console.WriteLine(res);
            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static long sum(int pattern, int[] a, int m, int start)
        {
            var res = 0;
            for (int i = 0; i < 20; i++)
            {
                if ((pattern & (1 << i)) != 0)
                {
                    res += a[i + start];
                    res %= m;
                }
            }

            return res;
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


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

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

        private static void Main(string[] args)
        {
            writer.WriteLine(Solve(args));
            writer.Flush();
        }

        private static long Solve(string[] args)
        {
            int n = Next();
            int m = Next();

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

            if (n == 1)
                return nn[0];

            int mid = n/2;
            var p1 = new List<long>();
            var p2 = new List<long>();

            for (int i = 0; i < mid; i++)
            {
                int cnt = p1.Count;
                for (int j = 0; j < cnt; j++)
                {
                    p1.Add((p1[j] + nn[i])%m);
                }
                p1.Add(nn[i]);
            }
            p1.Add(0);
            p1.Sort();

            for (int i = mid; i < n; i++)
            {
                int cnt = p2.Count;
                for (int j = 0; j < cnt; j++)
                {
                    p2.Add((p2[j] + nn[i])%m);
                }
                p2.Add(nn[i]);
            }

            p2.Add(0);

            long max = 0;
            foreach (long l in p2)
            {
                long v = m - l - 1;
                int index = p1.BinarySearch(v);
                if (index < 0)
                {
                    index = ~index;
                    index--;
                }
                if (index >= 0)
                {
                    max = Math.Max(max, l + p1[index]);
                }
            }

            return max;
        }

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


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

// (づ°ω°)づﾐe★゜・。。・゜゜・。。・゜☆゜・。。・゜゜・。。・゜
public class Solver
{
    public void Solve()
    {
        int n = ReadInt();
        int m = ReadInt();
        var v = ReadIntArray();

        if (n == 1)
        {
            Write(v[0] % m);
            return;
        }

        int na = n / 2;
        int nb = n - na;

        var a = new List<int>();
        for (int i = 0; i < 1 << na; i++)
        {
            long s = 0;
            for (int j = 0; j < na; j++)
                if ((i >> j & 1) == 1)
                    s += v[j];
            a.Add((int)(s % m));
        }

        var b = new List<int>();
        for (int i = 0; i < 1 << nb; i++)
        {
            long s = 0;
            for (int j = 0; j < nb; j++)
                if ((i >> j & 1) == 1)
                    s += v[j + na];
            b.Add((int)(s % m));
        }

        a.Sort();
        b.Sort();
        int ans = (a[a.Count - 1] + b[b.Count - 1]) % m;
        int p = b.Count - 1;
        for (int i = 0; i < a.Count; i++)
        {
            while (p >= 0 && a[i] + b[p] >= m)
                p--;
            if (p < 0)
                break;
            ans = Math.Max(ans, a[i] + b[p]);
        }

        Write(ans);
    }

    #region Main

    protected static TextReader reader;
    protected static TextWriter writer;
    static void Main()
    {
#if DEBUG
        reader = new StreamReader("..\\..\\input.txt");
        //reader = new StreamReader(Console.OpenStandardInput());
        writer = Console.Out;
        //writer = new StreamWriter("..\\..\\output.txt");
#else
        reader = new StreamReader(Console.OpenStandardInput());
        writer = new StreamWriter(Console.OpenStandardOutput());
        //reader = new StreamReader("input.txt");
        //writer = new StreamWriter("output.txt");
#endif
        try
        {
            new Solver().Solve();
            //var thread = new Thread(new Solver().Solve, 1024 * 1024 * 128);
            //thread.Start();
            //thread.Join();
        }
        catch (Exception ex)
        {
#if DEBUG
            Console.WriteLine(ex);
#else
            throw;
#endif
        }
        reader.Close();
        writer.Close();
    }

    #endregion

    #region Read / Write
    private static Queue<string> currentLineTokens = new Queue<string>();
    private static string[] ReadAndSplitLine() { return reader.ReadLine().Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries); }
    public static string ReadToken() { while (currentLineTokens.Count == 0)currentLineTokens = new Queue<string>(ReadAndSplitLine()); return currentLineTokens.Dequeue(); }
    public static int ReadInt() { return int.Parse(ReadToken()); }
    public static long ReadLong() { return long.Parse(ReadToken()); }
    public static double ReadDouble() { return double.Parse(ReadToken(), CultureInfo.InvariantCulture); }
    public static int[] ReadIntArray() { return ReadAndSplitLine().Select(int.Parse).ToArray(); }
    public static long[] ReadLongArray() { return ReadAndSplitLine().Select(long.Parse).ToArray(); }
    public static double[] ReadDoubleArray() { return ReadAndSplitLine().Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); }
    public static int[][] ReadIntMatrix(int numberOfRows) { int[][] matrix = new int[numberOfRows][]; for (int i = 0; i < numberOfRows; i++)matrix[i] = ReadIntArray(); return matrix; }
    public static int[][] ReadAndTransposeIntMatrix(int numberOfRows)
    {
        int[][] matrix = ReadIntMatrix(numberOfRows); int[][] ret = new int[matrix[0].Length][];
        for (int i = 0; i < ret.Length; i++) { ret[i] = new int[numberOfRows]; for (int j = 0; j < numberOfRows; j++)ret[i][j] = matrix[j][i]; } return ret;
    }
    public static string[] ReadLines(int quantity) { string[] lines = new string[quantity]; for (int i = 0; i < quantity; i++)lines[i] = reader.ReadLine().Trim(); return lines; }
    public static void WriteArray<T>(IEnumerable<T> array) { writer.WriteLine(string.Join(" ", array)); }
    public static void Write(params object[] array) { WriteArray(array); }
    public static void WriteLines<T>(IEnumerable<T> array) { foreach (var a in array)writer.WriteLine(a); }
    private class SDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {
        public new TValue this[TKey key]
        {
            get { return ContainsKey(key) ? base[key] : default(TValue); }
            set { base[key] = value; }
        }
    }
    private static T[] Init<T>(int size) where T : new() { var ret = new T[size]; for (int i = 0; i < size; i++)ret[i] = new T(); return ret; }
    #endregion
}


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

namespace Codeforces
{
    internal class Program
    {
        private const string Test = "E2";

        private static void Solve()
        {
            var MOD = 1000000007;
            var input = ReadIntArray();
            var n = input[0];
            var m = input[1];
            var k = input[2];
            var dp = new List<List<long>>();
            for (int i = 0; i <= 1001; i++)
            {
                dp.Add(new List<long>());
                for (int j = 0; j <= i; j++)
                {
                    if(j == 0 || j == i)
                        dp[i].Add(1);
                    else
                    {
                        dp[i].Add((dp[i-1][j-1] + dp[i - 1][j]) % MOD);
                    }
                }
            }
            var res = Math.Min(n - 1, m - 1) < 2*k ? 0: dp[n - 1][2*k]*dp[m - 1][2*k];
            res %= MOD;
            Console.WriteLine(res);
        }

        private static void Main()
        {
            if (Debugger.IsAttached)
            {
                Console.SetIn(new StreamReader(String.Format(@"..\..\..\..\Tests\{0}.in", Test)));
            }

            Solve();

            if (Debugger.IsAttached)
            {
                Console.In.Close();
                Console.SetIn(new StreamReader(Console.OpenStandardInput()));
                Console.ReadLine();
            }
        }

        #region Reader

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

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

        private static int[] ReadIntArray()
        {
            var input = Console.ReadLine().Split(' ').Select(Int32.Parse).ToArray();
            return input;
        }

        private static int ReadInt()
        {
            return Int32.Parse(Console.ReadLine());
        }

        private static long ReadLong()
        {
            return long.Parse(Console.ReadLine());
        }

        private static int ReadNextInt(string[] input, int index)
        {
            return Int32.Parse(input[index]);
        }

        #endregion
    }
}


using System;
using CompLib.Mathematics;
using CompLib.Util;

public class Program
{
    public void Solve()
    {
        var sc = new Scanner();
        long n = sc.NextLong();

        int m = sc.NextInt();

        var a = new Matrix(1, m);
        for (int i = 0; i < m; i++)
        {
            a[0, i] = 1;
        }

        var b = new Matrix(m, m);

        for (int i = 0; i < m - 1; i++)
        {
            b[i + 1, i] = 1;
        }

        b[0, m - 1] = 1;
        b[m - 1, m - 1] = 1;

        var c = Matrix.Pow(b, n);

        var d = a * c;

        Console.WriteLine(d[0, 0]);
    }

    public static void Main(string[] args) => new Program().Solve();
}

// https://bitbucket.org/camypaper/complib
namespace CompLib.Mathematics
{
    #region ModInt

    /// <summary>
    /// [0,<see cref="Mod"/>) までの値を取るような数
    /// </summary>
    public struct ModInt
    {
        /// <summary>
        /// 剰余を取る値．
        /// </summary>
        public const long Mod = (int) 1e9 + 7;

        /// <summary>
        /// 実際の数値．
        /// </summary>
        public long num;

        /// <summary>
        /// 値が <paramref name="n"/> であるようなインスタンスを構築します．
        /// </summary>
        /// <param name="n">インスタンスが持つ値</param>
        /// <remarks>パフォーマンスの問題上，コンストラクタ内では剰余を取りません．そのため，<paramref name="n"/> ∈ [0,<see cref="Mod"/>) を満たすような <paramref name="n"/> を渡してください．このコンストラクタは O(1) で実行されます．</remarks>
        public ModInt(long n)
        {
            num = n;
        }

        /// <summary>
        /// このインスタンスの数値を文字列に変換します．
        /// </summary>
        /// <returns>[0,<see cref="Mod"/>) の範囲内の整数を 10 進表記したもの．</returns>
        public override string ToString()
        {
            return num.ToString();
        }

        public static ModInt operator +(ModInt l, ModInt r)
        {
            l.num += r.num;
            if (l.num >= Mod) l.num -= Mod;
            return l;
        }

        public static ModInt operator -(ModInt l, ModInt r)
        {
            l.num -= r.num;
            if (l.num < 0) l.num += Mod;
            return l;
        }

        public static ModInt operator *(ModInt l, ModInt r)
        {
            return new ModInt(l.num * r.num % Mod);
        }

        public static implicit operator ModInt(long n)
        {
            n %= Mod;
            if (n < 0) n += Mod;
            return new ModInt(n);
        }

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(ModInt v, long k)
        {
            return Pow(v.num, k);
        }

        /// <summary>
        /// 与えられた 2 つの数値からべき剰余を計算します．
        /// </summary>
        /// <param name="v">べき乗の底</param>
        /// <param name="k">べき指数</param>
        /// <returns>繰り返し二乗法により O(N log N) で実行されます．</returns>
        public static ModInt Pow(long v, long k)
        {
            long ret = 1;
            for (k %= Mod - 1; k > 0; k >>= 1, v = v * v % Mod)
                if ((k & 1) == 1)
                    ret = ret * v % Mod;
            return new ModInt(ret);
        }

        /// <summary>
        /// 与えられた数の逆元を計算します．
        /// </summary>
        /// <param name="v">逆元を取る対象となる数</param>
        /// <returns>逆元となるような値</returns>
        /// <remarks>法が素数であることを仮定して，フェルマーの小定理に従って逆元を O(log N) で計算します．</remarks>
        public static ModInt Inverse(ModInt v)
        {
            return Pow(v, Mod - 2);
        }
    }

    #endregion

    #region Binomial Coefficient

    public class BinomialCoefficient
    {
        public ModInt[] fact, ifact;

        public BinomialCoefficient(int n)
        {
            fact = new ModInt[n + 1];
            ifact = new ModInt[n + 1];
            fact[0] = 1;
            for (int i = 1; i <= n; i++)
                fact[i] = fact[i - 1] * i;
            ifact[n] = ModInt.Inverse(fact[n]);
            for (int i = n - 1; i >= 0; i--)
                ifact[i] = ifact[i + 1] * (i + 1);
            ifact[0] = ifact[1];
        }

        public ModInt this[int n, int r]
        {
            get
            {
                if (n < 0 || n >= fact.Length || r < 0 || r > n) return 0;
                return fact[n] * ifact[n - r] * ifact[r];
            }
        }

        public ModInt RepeatedCombination(int n, int k)
        {
            if (k == 0) return 1;
            return this[n + k - 1, k];
        }
    }

    #endregion
}

// https://bitbucket.org/camypaper/complib
namespace CompLib.Mathematics
{
    using System.Diagnostics;
    using N = ModInt;

    #region Matrix

    public class Matrix
    {
        int row, col;
        public N[] mat;

        /// <summary>
        /// <paramref name="r"/> 行 <paramref name="c"/> 列目の要素へのアクセスを提供します。
        /// </summary>
        /// <param name="r">行の番号</param>
        /// <param name="c">列の番号</param>
        public N this[int r, int c]
        {
            get { return mat[r * col + c]; }
            set { mat[r * col + c] = value; }
        }

        public Matrix(int r, int c)
        {
            row = r;
            col = c;
            mat = new N[row * col];
        }

        public static Matrix operator *(Matrix l, Matrix r)
        {
            Debug.Assert(l.col == r.row);
            var ret = new Matrix(l.row, r.col);
            for (int i = 0; i < l.row; i++)
            for (int k = 0; k < l.col; k++)
            for (int j = 0; j < r.col; j++)
                ret.mat[i * r.col + j] = (ret.mat[i * r.col + j] + l.mat[i * l.col + k] * r.mat[k * r.col + j]);
            return ret;
        }

        /// <summary>
        /// <paramref name="m"/>^<paramref name="n"/> を O(<paramref name="m"/>^3 log <paramref name="n"/>) で計算します。
        /// </summary>
        public static Matrix Pow(Matrix m, long n)
        {
            var ret = new Matrix(m.row, m.col);
            for (int i = 0; i < m.row; i++)
                ret.mat[i * m.col + i] = 1;
            for (; n > 0; m *= m, n >>= 1)
                if ((n & 1) == 1)
                    ret = ret * m;
            return ret;
        }

        public N[][] Items
        {
            get
            {
                var a = new N[row][];
                for (int i = 0; i < row; i++)
                {
                    a[i] = new N[col];
                    for (int j = 0; j < col; j++)
                        a[i][j] = mat[i * col + j];
                }

                return a;
            }
        }
    }

    #endregion
}

namespace CompLib.Util
{
    using System;
    using System.Linq;

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            while (_index >= _line.Length)
            {
                _line = Console.ReadLine().Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            _line = Console.ReadLine().Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using static Template;
using static System.Console;
using static System.Convert;
using static System.Math;
using Pi = Pair<int, int>;
using Number = System.Int64;

class Solver
{
    public void Solve()
    {
        long num;int m;
        Input.Make(out num, out m);
        if (num < m) Fail(1);
        var mt = new Math.Matrix(m);
        mt[0][0] = 1;
        mt[0][m - 1] = 1;
        for (var i = 1; i < m; i++)
            mt[i][i - 1] = 1;
        mt = mt.Pow(num - m + 1);
        var res = 0L;
        for(var i=0;i<m;i++)
        {
            res += mt[0][i];
            res %= Input.MOD;
        }
        WriteLine(res);
    }
}
#region Matrix
namespace Math
{
    using NUM = System.Int64;
    public class Matrix
    {
        private NUM[][] item { get; }
        public int Height { get; }
        public int Width { get; }
        public static NUM e { get; set; }
        //add,mulは環をなす必要がある
        public static Func<NUM, NUM, NUM> add { get; set; }
        public static Func<NUM, NUM, NUM> mul { get; set; }
        static Matrix()
        {
            const int mod = 1000000007; e = 1;
            add = (a, b) => a + b >= mod ? a + b - mod : a + b; mul = (a, b) => (a * b) % mod;
        }
        public NUM[] this[int i]
        { get { return item[i]; } set { item[i] = value; } }
        public NUM this[int i1, int i2]
        {
            get { return item[i1][i2]; }
            set { item[i1][i2] = value; }
        }
        public Matrix(int size) : this(size, size) { }
        public Matrix(int height, int width)
        {
            Height = height;
            Width = width;
            item = Enumerable.Repeat(0, height).Select(_ => new NUM[width]).ToArray();
        }

        private static Matrix E(int size)
        {
            var tm = new Matrix(size, size);
            for (var i = 0; i < size; i++)
                tm[i, i] = e;
            return tm;
        }

        public static Matrix Trans(Matrix m)
        {
            var n = m.Width; var p = m.Height;
            var tm = new Matrix(n, p);
            for (var i = 0; i < n; i++)
            {
                for (var j = 0; j < p; j++)
                    tm[i, j] = m[j, i];
            }
            return tm;
        }
        private static NUM Dot(NUM[] ar1, NUM[] ar2)
        {
            var tm = default(NUM);
            for (var i = 0; i < ar1.Length; i++)
                tm = add(tm, mul(ar1[i], ar2[i]));
            return tm;
        }
        public static Matrix Add(Matrix m1, Matrix m2)
        {
            var tm = new Matrix(m1.Height, m1.Width);
            for (var i = 0; i < m1.Height; i++)
                for (var j = 0; j < m1.Width; j++)
                    tm[i, j] = add(m1[i, j], m2[i, j]);
            return tm;
        }
        public static NUM[] Mul(Matrix m, NUM[] ar)
            => Enumerable.Range(0, m.Height).Select(v => Dot(m[v], ar)).ToArray();

        public static Matrix Mul(Matrix m1, Matrix m2)
        {
            var tr = Trans(m2);
            var tm = new Matrix(m1.Height, m2.Width);
            for (var i = 0; i < m1.Height; i++)
                tm[i] = Mul(tr, m1[i]);
            return tm;
        }
        public static Matrix operator +(Matrix l, Matrix r)
            => Add(l, r);
        public static Matrix operator *(Matrix l, Matrix r)
            => Mul(l, r);
        public static NUM[] operator *(Matrix l, NUM[] r)
            => Mul(l, r);

        public Matrix Pow(long n)
        {
            if (n == 0) return E(Height);
            var tm = Pow(n / 2);
            if (n % 2 == 0) return Mul(tm, tm);
            else return Mul(Mul(tm, tm), this);
        }
    }
}
#endregion
#region Template
public class Template
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T num, T val) where T : IComparable<T>
    { if (num.CompareTo(val) == 1) { num = val; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T num, T val) where T : IComparable<T>
    { if (num.CompareTo(val) == -1) { num = val; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T v1, ref T v2)
    { var t = v2; v2 = v1; v1 = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static T[] Create<T>(int n, Func<T> f)
        => Enumerable.Repeat(0, n).Select(_ => f()).ToArray();
    public static void Fail() => Fail("No");
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
    static void Main(string[] args)
    {
        var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
        Console.SetOut(sw);
        var p = new Solver();
        for (var i = 1; i > 0; --i)
            p.Solve();
        Console.Out.Flush();
    }
}

public class Input
{
    public static string read => Console.ReadLine().Trim();
    public static int[] ar => read.Split(' ').Select(int.Parse).ToArray();
    public static int num => Convert.ToInt32(read);
    public static long[] arL => read.Split(' ').Select(long.Parse).ToArray();
    public static long numL => Convert.ToInt64(read);
    public static char[][] grid(int h)
        => Create(h, () => read.ToCharArray());
    public static int[] ar1D(int n)
        => Create(n, () => num);
    public static long[] arL1D(int n)
        => Create(n, () => numL);
    public static string[] strs(int n)
        => Create(n, () => read);
    public static int[][] ar2D(int n)
        => Create(n, () => ar);
    public static long[][] arL2D(int n)
        => Create(n, () => arL);
    public static List<T>[] edge<T>(int n)
        => Create(n, () => new List<T>());
    public static void Make<T1, T2>(out T1 v1, out T2 v2)
    {
        v1 = Next<T1>();
        v2 = Next<T2>();
    }
    public static void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3)
    {
        Make(out v1, out v2);
        v3 = Next<T3>();
    }
    public static void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4)
    {
        Make(out v1, out v2, out v3);
        v4 = Next<T4>();
    }
    public static void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5)
    {
        Make(out v1, out v2, out v3, out v4);
        v5 = Next<T5>();
    }
    public static void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6)
    {
        Make(out v1, out v2, out v3, out v4, out v5);
        v6 = Next<T6>();
    }
    static Input()
    {
        sc = new Queue<string>();
        dic = new Dictionary<Type, Func<string, object>>();
        dic[typeof(int)] = s => int.Parse(s);
        dic[typeof(long)] = s => long.Parse(s);
        dic[typeof(char)] = s => char.Parse(s);
        dic[typeof(double)] = s => double.Parse(s);
        dic[typeof(uint)] = s => uint.Parse(s);
        dic[typeof(ulong)] = s => ulong.Parse(s);
        dic[typeof(string)] = s => s;
    }
    private static Dictionary<Type, Func<string, object>> dic;
    private static Queue<string> sc;
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static T Next<T>() { if (sc.Count == 0) foreach (var item in read.Split(' ')) sc.Enqueue(item); return (T)dic[typeof(T)](sc.Dequeue()); }
    public const int MOD = 1000000007;
}

public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1;
    public T2 v2;
    public Pair() { v1 = Input.Next<T1>(); v2 = Input.Next<T2>(); }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString()
        => $"{v1.ToString()} {v2.ToString()}";
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3;
    public Pair() : base() { v3 = Input.Next<T3>(); }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString()
        => $"{base.ToString()} {v3.ToString()}";
}
#endregion


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//неправильный ответ на тесте 15
namespace F
{
    class Program
    {
        static Tree[] wt;
        class Tree
        {
            public long ves;
            public long ves_;
            public int nn;//индек первого элемента
            public int nk;//индек последнего элемента
            public Tree l;
            public Tree r;
            public Tree p;
            public Tree(int[] m, int[] a, int i1, int ik, Tree p1)
            {
                nn = i1;
                nk = ik;
                if (i1 == ik)
                {
                    l = null;
                    r = null;
                    ves = m[i1];
                    ves_ = ((long)(a[i1] - i1) * (long)m[i1]) % (long)(1000000007);
                    //ves_ = ((long)(a[i1] - i1) * (long)m[i1]) ;
                    wt[i1] = this;
                }
                else
                {
                    int s = (ik + i1 + 1) / 2;
                    l = new Tree(m, a, i1, s - 1, this);
                    r = new Tree(m, a, s, ik, this);
                    ves = l.ves + r.ves;
                    ves_ = (l.ves_ + r.ves_) % (long)(1000000007);
                }
                p = p1;
                if (ves < 0) Console.WriteLine("ОЙ");
                if (ves_ < 0) Console.WriteLine("ОЙ");
                //if (ves >= 1000000007) Console.WriteLine("ОЙ");
                if (ves_ >= 1000000007) Console.WriteLine("ОЙ");
            }
        }

        static long FindVes(Tree t1, Tree tn, bool t)//t=true ves;t=false ves_;
        {
            long ves = 0;
            int x1 = t1.nn;
            int y1 = tn.nk;
            if (y1 < x1) return 0;
            Tree ti = wt[x1];
            while (ti.nk < y1) ti = ti.p;
            if (t) ves = (long)ti.ves;
            else ves = (long)ti.ves_;
            Tree tiv = ti;
            while (ti.nn < x1)
            {
                if (ti.r.nn <= x1)
                {
                    if (t) ves = ves - (long)ti.l.ves;
                    else ves = (ves - (long)ti.l.ves_ + (long)(1000000007)) % (long)(1000000007);
                    ti = ti.r;
                }
                else
                {
                    ti = ti.l;
                }
            }
            ti = tiv;
            while (ti.nk > y1)
            {
                if (ti.l.nk >= y1)
                {
                    if (t) ves = ves - (long)ti.r.ves;
                    else ves = (ves - (long)ti.r.ves_ + (long)(1000000007)) % (long)(1000000007);
                    ti = ti.l;
                }
                else
                {
                    ti = ti.r;
                }
            }
            return ves;
        }

        static void Main(string[] args)
        {
            TextReader sr = Console.In;
            //StreamReader sr = new StreamReader("in115.txt");
            string[] s = sr.ReadLine().Split();
            int n = Convert.ToInt32(s[0]);
            int q = Convert.ToInt32(s[1]);
            s = sr.ReadLine().Split();
            string[] s1 = sr.ReadLine().Split();
            int[] a = new int[n];
            int[] w = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = Convert.ToInt32(s[i]);
                w[i] = Convert.ToInt32(s1[i]);
            }
            //решение
            wt = new Tree[n];
            Tree t1 = new Tree(w, a, 0, n - 1, null);

            int ll;
            int rr;
            int id, nw;
            bool zapros1;
            Tree ti;
            List<int> res = new List<int>();
            for (int i = 0; i < q; i++)
            {
                s = sr.ReadLine().Split();
                ll = Convert.ToInt32(s[0]);
                if (ll < 0) zapros1 = true; else zapros1 = false;
                id = -1 - ll;
                ll--;
                nw = Convert.ToInt32(s[1]);
                rr = nw - 1;
                if (zapros1)
                {
                    ti = wt[id];
                    long delta = (long)nw - ti.ves;
                    long delta_ = (((long)(a[id] - id) * (long)nw)) % (long)(1000000007) - ti.ves_;
                    w[id] = nw;
                    while (ti != null)
                    {
                        ti.ves = ti.ves + delta;
                        ti.ves_ = (ti.ves_ + delta_ + (long)(1000000007)) % (long)(1000000007);
                        ti = ti.p;
                    }
                }
                else
                {
                    if (ll == rr)
                    {
                        res.Add(0);
                    }
                    else if ((rr - ll) == (a[rr] - a[ll]))
                    {
                        res.Add(0);
                    }
                    else if ((rr - ll) == 1)
                    {
                        if (w[ll] > w[rr])
                        {
                            res.Add((int)(((long)(a[rr] - a[ll] - 1) * (long)w[rr]) % (long)(1000000007)));
                        }
                        else
                        {
                            res.Add((int)(((long)(a[rr] - a[ll] - 1) * (long)w[ll]) % (long)(1000000007)));
                        }
                    }
                    else
                    {
                        //найти вес отрезка
                        //int x1 = x - 1;
                        //int y1 = y - 1;
                        long ves = FindVes(wt[ll], wt[rr], true);
                        long vl, vr, vv;
                        int iis, iiss;
                        int iisll = ll, iislr = rr;
                        iis = (ll + rr + 1) / 2;
                        vl = FindVes(wt[ll], wt[iis - 1], true);
                        vr = FindVes(wt[iis + 1], wt[rr], true);
                        while (true)
                        {
                            if ((vl + w[iis] > vr) && (vr + w[iis] > vl)) break;
                            if (vl + w[iis] == vr)
                            {
                                if (w[iis] >= w[iis + 1]) break;
                                else
                                {
                                    iis++;
                                    break;
                                }
                            }
                            if (vr + w[iis] == vl)
                            {
                                if (w[iis] >= w[iis - 1]) break;
                                else
                                {
                                    iis--;
                                    break;
                                }
                            }
                            if ((vl + w[iis]) > (vr + w[iis]))
                            {
                                iiss = (iisll + iis) / 2;
                                vv = FindVes(wt[iiss + 1], wt[iis - 1], true);
                                vl = vl - vv - w[iiss];
                                vr = vr + vv + w[iis];
                                iislr = iis;
                                iis = iiss;
                            }
                            else
                            {
                                iiss = (iislr + iis + 1) / 2;
                                vv = FindVes(wt[iis + 1], wt[iiss - 1], true);
                                vl = vl + vv + w[iis];
                                vr = vr - vv - w[iiss];
                                iisll = iis;
                                iis = iiss;
                            }
                        }
                        //long r1 = 0;
                        //for (int j = ll; j < iis; j++)
                        //{
                        //    r1 = (r1 + ((long)w[j] * (long)(a[iis] - a[j] - (iis - j)))) % 1000000007;
                        //}
                        //for (int j = iis + 1; j <= rr; j++)
                        //{
                        //    r1 = (r1 + ((long)w[j] * (long)(a[j] - a[iis] - (j - iis)))) % 1000000007;
                        //}
                        long r = 0;
                        if (iis > ll)
                        {
                            r = (r - (FindVes(wt[ll], wt[iis - 1], false) % (long)(1000000007)) + (long)(1000000007)) % (long)(1000000007);
                            r = (r + ((long)(a[iis] - iis)) * (FindVes(wt[ll], wt[iis - 1], true) % (long)(1000000007))) % (long)(1000000007);

                        }
                        if (iis < rr)
                        {
                            r = (r + (FindVes(wt[iis + 1], wt[rr], false)) % (long)(1000000007)) % (long)(1000000007);
                            r = (r - ((long)(a[iis] - iis) * (FindVes(wt[iis + 1], wt[rr], true) % (long)(1000000007))) % (long)(1000000007) + (long)(1000000007)) % (long)(1000000007);
                        }
                        res.Add((int)r);
                    }
                }
            }
            Console.WriteLine(string.Join("\n", res));
        }
    }
}


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

namespace F
{
    class Program
    {
        static Tree[] wt;
        class Tree
        {
            public long ves;
            public long ves_;
            public int nn;//индек первого элемента
            public int nk;//индек последнего элемента
            public Tree l;
            public Tree r;
            public Tree p;
            public Tree(int[] m, int[] a, int i1, int ik, Tree p1)
            {
                nn = i1;
                nk = ik;
                if (i1 == ik)
                {
                    l = null;
                    r = null;
                    ves = m[i1];
                    ves_ = ((long)(a[i1] - i1) * (long)m[i1]) % (long)(1000000007);
                    wt[i1] = this;
                }
                else
                {
                    int s = (ik + i1 + 1) / 2;
                    l = new Tree(m, a, i1, s - 1, this);
                    r = new Tree(m, a, s, ik, this);
                    ves = l.ves + r.ves;
                    ves_ = (l.ves_ + r.ves_) % (long)(1000000007);
                }
                p = p1;
            }
        }

        static long FindVes(Tree t1, Tree tn, bool t)//t=true ves;t=false ves_;
        {
            long ves = 0;
            int x1 = t1.nn;
            int y1 = tn.nk;
            if (y1 < x1) return 0;
            Tree ti = wt[x1];
            while (ti.nk < y1) ti = ti.p;
            if (t) ves = (long)ti.ves;
            else ves = (long)ti.ves_;
            Tree tiv = ti;
            while (ti.nn < x1)
            {
                if (ti.r.nn <= x1)
                {
                    if (t) ves = ves - (long)ti.l.ves;
                    else ves = (ves - (long)ti.l.ves_ + (long)(1000000007)) % (long)(1000000007);
                    ti = ti.r;
                }
                else
                {
                    ti = ti.l;
                }
            }
            ti = tiv;
            while (ti.nk > y1)
            {
                if (ti.l.nk >= y1)
                {
                    if (t) ves = ves - (long)ti.r.ves;
                    else ves = (ves - (long)ti.r.ves_ + (long)(1000000007)) % (long)(1000000007);
                    ti = ti.l;
                }
                else
                {
                    ti = ti.r;
                }
            }
            return ves;
        }

        static void Main(string[] args)
        {
            TextReader sr = Console.In;
            //StreamReader sr = new StreamReader("in1.txt");
            string[] s = sr.ReadLine().Split();
            int n = Convert.ToInt32(s[0]);
            int q = Convert.ToInt32(s[1]);
            s = sr.ReadLine().Split();
            string[] s1 = sr.ReadLine().Split();
            int[] a = new int[n];
            int[] w = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = Convert.ToInt32(s[i]);
                w[i] = Convert.ToInt32(s1[i]);
            }
            //решение
            wt = new Tree[n];
            Tree t1 = new Tree(w, a, 0, n - 1, null);

            int ll;
            int rr;
            int id, nw;
            bool zapros1;
            Tree ti;
            List<int> res = new List<int>();
            for (int i = 0; i < q; i++)
            {
                s = sr.ReadLine().Split();
                ll = Convert.ToInt32(s[0]);
                if (ll < 0) zapros1 = true; else zapros1 = false;
                id = -1 - ll;
                ll--;
                nw = Convert.ToInt32(s[1]);
                rr = nw - 1;
                if (zapros1)
                {
                    ti = wt[id];
                    long delta = (long)nw - ti.ves;
                    long delta_ = (((long)(a[id] - id) * (long)nw)) % (long)(1000000007) - ti.ves_;
                    w[id] = nw;
                    while (ti != null)
                    {
                        ti.ves = ti.ves + delta;
                        ti.ves_ = (ti.ves_ + delta_ + (long)(1000000007)) % (long)(1000000007);
                        ti = ti.p;
                    }
                }
                else
                {
                    if (ll == rr)
                    {
                        res.Add(0);
                    }
                    else if ((rr - ll) == (a[rr] - a[ll]))
                    {
                        res.Add(0);
                    }
                    else if ((rr - ll) == 1)
                    {
                        if (w[ll] > w[rr])
                        {
                            res.Add((int)(((long)(a[rr] - a[ll] - 1) * (long)w[rr]) % (long)(1000000007)));
                        }
                        else
                        {
                            res.Add((int)(((long)(a[rr] - a[ll] - 1) * (long)w[ll]) % (long)(1000000007)));
                        }
                    }
                    else
                    {
                        //найти вес отрезка
                        long ves = FindVes(wt[ll], wt[rr], true);
                        long vl, vr, vv;
                        int iis, iiss;
                        int iisll = ll, iislr = rr;
                        iis = (ll + rr + 1) / 2;
                        vl = FindVes(wt[ll], wt[iis - 1], true);
                        vr = FindVes(wt[iis + 1], wt[rr], true);
                        while (true)
                        {
                            if ((vl + w[iis] > vr) && (vr + w[iis] > vl)) break;
                            if (vl + w[iis] == vr)
                            {
                                if (w[iis] < w[iis + 1]) iis++;
                                break;
                            }
                            if (vr + w[iis] == vl)
                            {
                                if (w[iis] < w[iis - 1]) iis--;
                                break;
                            }
                            if ((vl) > (vr))
                            {
                                iiss = (iisll + iis) / 2;
                                vv = FindVes(wt[iiss + 1], wt[iis - 1], true);
                                vl = vl - vv - w[iiss];
                                vr = vr + vv + w[iis];
                                iislr = iis;
                                iis = iiss;
                            }
                            else
                            {
                                iiss = (iislr + iis + 1) / 2;
                                vv = FindVes(wt[iis + 1], wt[iiss - 1], true);
                                vl = vl + vv + w[iis];
                                vr = vr - vv - w[iiss];
                                iisll = iis;
                                iis = iiss;
                            }
                        }
                        long r = 0;
                        if (iis > ll)
                        {
                            r = (r - (FindVes(wt[ll], wt[iis - 1], false) % (long)(1000000007)) + (long)(1000000007)) % (long)(1000000007);
                            r = (r + (long)(a[iis] - iis) * (FindVes(wt[ll], wt[iis - 1], true) % (long)(1000000007))) % (long)(1000000007);

                        }
                        if (iis < rr)
                        {
                            r = (r + (FindVes(wt[iis + 1], wt[rr], false)) % (long)(1000000007)) % (long)(1000000007);
                            r = (r - (long)(a[iis] - iis) * (FindVes(wt[iis + 1], wt[rr], true) % (long)(1000000007)) % (long)(1000000007) + (long)(1000000007)) % (long)(1000000007);
                        }
                        res.Add((int)r);
                    }
                }
            }
            Console.WriteLine(string.Join("\n", res));
        }
    }
}


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

namespace F
{
    class Program
    {
        static Tree[] wt;
        class Tree
        {
            public long ves;
            public long ves_;
            public int nn;//индек первого элемента
            public int nk;//индек последнего элемента
            public Tree l;
            public Tree r;
            public Tree p;
            public Tree(int[] m, int[] a, int i1, int ik, Tree p1)
            {
                nn = i1;
                nk = ik;
                if (i1 == ik)
                {
                    l = null;
                    r = null;
                    ves = m[i1];
                    ves_ = ((long)(a[i1] - i1) * (long)m[i1]) % (long)(1000000007);
                    wt[i1] = this;
                }
                else
                {
                    int s = (ik + i1 + 1) / 2;
                    l = new Tree(m, a, i1, s - 1, this);
                    r = new Tree(m, a, s, ik, this);
                    ves = l.ves + r.ves;
                    ves_ = (l.ves_ + r.ves_) % (long)(1000000007);
                }
                p = p1;
            }
        }

        static long FindVes(Tree t1, Tree tn, bool t)//t=true ves;t=false ves_;
        {
            long ves = 0;
            int x1 = t1.nn;
            int y1 = tn.nk;
            if (y1 < x1) return 0;
            Tree ti = wt[x1];
            long sub = 0;
            while (ti.nk < y1)
            {
                if (ti.p.r == ti && ti.p.l!=null)
                {
                    if (t) sub = sub + ti.p.l.ves;
                    else sub = (sub + ti.p.l.ves_) % (long)(1000000007);
                }
                ti = ti.p;
            }
            if (t) ves = (long)ti.ves;
            else ves = (long)ti.ves_;
            if (t) ves =ves-sub;
            else ves =(ves-sub+ +(long)(1000000007)) % (long)(1000000007);
            //Tree tiv = ti;
            //while (ti.nn < x1)
            //{
            //    if (ti.r.nn <= x1)
            //    {
            //        if (t) ves = ves - (long)ti.l.ves;
            //        else ves = (ves - (long)ti.l.ves_ + (long)(1000000007)) % (long)(1000000007);
            //        ti = ti.r;
            //    }
            //    else
            //    {
            //        ti = ti.l;
            //    }
            //}
            //ti = tiv;
            while (ti.nk > y1)
            {
                if (ti.l.nk >= y1)
                {
                    if (t) ves = ves - (long)ti.r.ves;
                    else ves = (ves - (long)ti.r.ves_ + (long)(1000000007)) % (long)(1000000007);
                    ti = ti.l;
                }
                else
                {
                    ti = ti.r;
                }
            }
            return ves;
        }

        static void Main(string[] args)
        {
            TextReader sr = Console.In;
            //StreamReader sr = new StreamReader("in1.txt");
            string[] s = sr.ReadLine().Split();
            int n = Convert.ToInt32(s[0]);
            int q = Convert.ToInt32(s[1]);
            s = sr.ReadLine().Split();
            string[] s1 = sr.ReadLine().Split();
            int[] a = new int[n];
            int[] w = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = Convert.ToInt32(s[i]);
                w[i] = Convert.ToInt32(s1[i]);
            }
            //решение
            wt = new Tree[n];
            Tree t1 = new Tree(w, a, 0, n - 1, null);

            int ll;
            int rr;
            int id, nw;
            bool zapros1;
            Tree ti;
            List<int> res = new List<int>();
            for (int i = 0; i < q; i++)
            {
                s = sr.ReadLine().Split();
                ll = Convert.ToInt32(s[0]);
                if (ll < 0) zapros1 = true; else zapros1 = false;
                id = -1 - ll;
                ll--;
                nw = Convert.ToInt32(s[1]);
                rr = nw - 1;
                if (zapros1)
                {
                    ti = wt[id];
                    long delta = (long)nw - ti.ves;
                    long delta_ = (((long)(a[id] - id) * (long)nw)) % (long)(1000000007) - ti.ves_;
                    w[id] = nw;
                    while (ti != null)
                    {
                        ti.ves = ti.ves + delta;
                        ti.ves_ = (ti.ves_ + delta_ + (long)(1000000007)) % (long)(1000000007);
                        ti = ti.p;
                    }
                }
                else
                {
                    if (ll == rr)
                    {
                        res.Add(0);
                    }
                    else if ((rr - ll) == (a[rr] - a[ll]))
                    {
                        res.Add(0);
                    }
                    else if ((rr - ll) == 1)
                    {
                        if (w[ll] > w[rr])
                        {
                            res.Add((int)(((long)(a[rr] - a[ll] - 1) * (long)w[rr]) % (long)(1000000007)));
                        }
                        else
                        {
                            res.Add((int)(((long)(a[rr] - a[ll] - 1) * (long)w[ll]) % (long)(1000000007)));
                        }
                    }
                    else
                    {
                        //найти вес отрезка
                        long ves = FindVes(wt[ll], wt[rr], true);
                        long vl, vr, vv;
                        int iis, iiss;
                        int iisll = ll, iislr = rr;
                        iis = (ll + rr + 1) / 2;
                        vl = FindVes(wt[ll], wt[iis - 1], true);
                        vr = FindVes(wt[iis + 1], wt[rr], true);
                        while (true)
                        {
                            if ((vl + w[iis] > vr) && (vr + w[iis] > vl)) break;
                            if (vl + w[iis] == vr)
                            {
                                if (w[iis] < w[iis + 1]) iis++;
                                break;
                            }
                            if (vr + w[iis] == vl)
                            {
                                if (w[iis] < w[iis - 1]) iis--;
                                break;
                            }
                            if ((vl) > (vr))
                            {
                                iiss = (iisll + iis) / 2;
                                vv = FindVes(wt[iiss + 1], wt[iis - 1], true);
                                vl = vl - vv - w[iiss];
                                vr = vr + vv + w[iis];
                                iislr = iis;
                                iis = iiss;
                            }
                            else
                            {
                                iiss = (iislr + iis + 1) / 2;
                                vv = FindVes(wt[iis + 1], wt[iiss - 1], true);
                                vl = vl + vv + w[iis];
                                vr = vr - vv - w[iiss];
                                iisll = iis;
                                iis = iiss;
                            }
                        }
                        long r = 0;
                        if (iis > ll)
                        {
                            r = (r - (FindVes(wt[ll], wt[iis - 1], false) % (long)(1000000007)) + (long)(1000000007)) % (long)(1000000007);
                            r = (r + (long)(a[iis] - iis) * (FindVes(wt[ll], wt[iis - 1], true) % (long)(1000000007))) % (long)(1000000007);

                        }
                        if (iis < rr)
                        {
                            r = (r + (FindVes(wt[iis + 1], wt[rr], false)) % (long)(1000000007)) % (long)(1000000007);
                            r = (r - (long)(a[iis] - iis) * (FindVes(wt[iis + 1], wt[rr], true) % (long)(1000000007)) % (long)(1000000007) + (long)(1000000007)) % (long)(1000000007);
                        }
                        res.Add((int)r);
                    }
                }
            }
            Console.WriteLine(string.Join("\n", res));
        }
    }
}


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

namespace CSharpParser
{
    public class Solution : SolutionBase
    {
        protected override void Solve()
        {
            int n;
            Next(out n);
            int s;
            Next(out s);
            --s;
            int k;
            Next(out k);
            var a = NextArray<int>(n);
            string c;
            Next(out c);
            var m = a.Sum() + 1;
            var d = new int[n, m];
            for (var i = 0; i < n; i++)
            {
                for (var j = 0; j < m; j++)
                    d[i, j] = int.MaxValue;
                d[i, a[i]] = Math.Abs(s - i);
            }
            var u = new bool[n];
            while (true)
            {
                var i = -1;
                for (var l = 0; l < n; l++)
                    if (!u[l] && (i == -1 || a[i] > a[l]))
                        i = l;
                if (i == -1) break;
                u[i] = true;
                for (var j = 0; j < m; j++)
                    if (d[i, j] != int.MaxValue)
                        for (var l = 0; l < n; l++)
                            if (a[l] > a[i] && c[l] != c[i])
                                d[l, j + a[l]] = Math.Min(d[l, j + a[l]], d[i, j] + Math.Abs(i - l));
            }
            var ans = int.MaxValue;
            for (var i = 0; i < n; i++)
                for (var j = k; j < m; j++)
                    ans = Math.Min(ans, d[i, j]);
            PrintLine(ans == int.MaxValue ? -1 : ans);
        }
    }

    public static class Algorithm
    {
        private static readonly Random Rnd = new Random();

        public static void Swap<T>(ref T a, ref T b)
        {
            var temp = a;
            a = b;
            b = temp;
        }

        public static T Max<T>(params T[] a)
        {
            var ans = a[0];
            var comp = Comparer<T>.Default;
            for (var i = 1; i < a.Length; i++) ans = comp.Compare(ans, a[i]) >= 0 ? ans : a[i];
            return ans;
        }

        public static T Min<T>(params T[] a)
        {
            var ans = a[0];
            var comp = Comparer<T>.Default;
            for (var i = 1; i < a.Length; i++) ans = comp.Compare(ans, a[i]) <= 0 ? ans : a[i];
            return ans;
        }

        public static void RandomShuffle<T>(IList<T> a, int index, int length)
        {
            if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
            var last = index + length;
            if (last > a.Count) throw new ArgumentException();
            for (var i = index + 1; i < last; i++)
            {
                var j = Rnd.Next(index, i + 1);
                var t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }

        public static void RandomShuffle<T>(IList<T> a)
        {
            RandomShuffle(a, 0, a.Count);
        }

        public static bool NextPermutation<T>(IList<T> a, int index, int length, Comparison<T> compare = null)
        {
            compare = compare ?? Comparer<T>.Default.Compare;
            if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
            var last = index + length;
            if (last > a.Count) throw new ArgumentException();
            for (var i = last - 1; i > index; i--)
                if (compare(a[i], a[i - 1]) > 0)
                {
                    var j = i + 1;
                    for (; j < last; j++) if (compare(a[j], a[i - 1]) <= 0) break;
                    var t = a[i - 1];
                    a[i - 1] = a[j - 1];
                    a[j - 1] = t;
                    for (; i < last - 1; i++, last--)
                    {
                        t = a[i];
                        a[i] = a[last - 1];
                        a[last - 1] = t;
                    }
                    return true;
                }
            for (var i = index; i < last - 1; i++, last--)
            {
                var t = a[i];
                a[i] = a[last - 1];
                a[last - 1] = t;
            }
            return false;
        }

        public static bool NextPermutation<T>(IList<T> a, Comparison<T> compare = null)
        {
            return NextPermutation(a, 0, a.Count, compare);
        }

        public static bool PrevPermutation<T>(IList<T> a, int index, int length, Comparison<T> compare = null)
        {
            compare = compare ?? Comparer<T>.Default.Compare;
            if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
            var last = index + length;
            if (last > a.Count) throw new ArgumentException();
            for (var i = last - 1; i > index; i--)
                if (compare(a[i], a[i - 1]) < 0)
                {
                    var j = i + 1;
                    for (; j < last; j++) if (compare(a[j], a[i - 1]) >= 0) break;
                    var t = a[i - 1];
                    a[i - 1] = a[j - 1];
                    a[j - 1] = t;
                    for (; i < last - 1; i++, last--)
                    {
                        t = a[i];
                        a[i] = a[last - 1];
                        a[last - 1] = t;
                    }
                    return true;
                }
            for (var i = index; i < last - 1; i++, last--)
            {
                var t = a[i];
                a[i] = a[last - 1];
                a[last - 1] = t;
            }
            return false;
        }

        public static bool PrevPermutation<T>(IList<T> a, Comparison<T> compare = null)
        {
            return PrevPermutation(a, 0, a.Count, compare);
        }

        public static int LowerBound<T>(IList<T> a, int index, int length, T value, Comparison<T> compare = null)
        {
            compare = compare ?? Comparer<T>.Default.Compare;
            if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
            if (index + length > a.Count) throw new ArgumentException();
            var ans = index;
            var last = index + length;
            var p2 = 1;
            while (p2 <= length) p2 *= 2;
            for (p2 /= 2; p2 > 0; p2 /= 2) if (ans + p2 <= last && compare(a[ans + p2 - 1], value) < 0) ans += p2;
            return ans;
        }

        public static int LowerBound<T>(IList<T> a, T value, Comparison<T> compare = null)
        {
            return LowerBound(a, 0, a.Count, value, compare);
        }

        public static int UpperBound<T>(IList<T> a, int index, int length, T value, Comparison<T> compare = null)
        {
            compare = compare ?? Comparer<T>.Default.Compare;
            if (index < 0 || length < 0) throw new ArgumentOutOfRangeException();
            if (index + length > a.Count) throw new ArgumentException();
            var ans = index;
            var last = index + length;
            var p2 = 1;
            while (p2 <= length) p2 *= 2;
            for (p2 /= 2; p2 > 0; p2 /= 2) if (ans + p2 <= last && compare(a[ans + p2 - 1], value) <= 0) ans += p2;
            return ans;
        }

        public static int UpperBound<T>(IList<T> a, T value, Comparison<T> compare = null)
        {
            return UpperBound(a, 0, a.Count, value, compare);
        }

        public static void Fill<T>(this IList<T> array, T value) where T : struct
        {
            for (var i = 0; i < array.Count; i++)
                array[i] = value;
        }

        public static void Fill<T>(this IList<T> array, Func<int, T> func)
        {
            for (var i = 0; i < array.Count; i++)
                array[i] = func(i);
        }
    }

    public class InStream : IDisposable
    {
        protected readonly TextReader InputStream;
        private string[] _tokens;
        private int _pointer;

        private InStream(TextReader inputStream)
        {
            InputStream = inputStream;
        }

        public static InStream FromString(string str)
        {
            return new InStream(new StringReader(str));
        }

        public static InStream FromFile(string str)
        {
            return new InStream(new StreamReader(str));
        }

        public static InStream FromConsole()
        {
            return new InStream(Console.In);
        }

        public string NextLine()
        {
            try
            {
                return InputStream.ReadLine();
            }
            catch (Exception)
            {
                return null;
            }
        }

        private string NextString()
        {
            try
            {
                while (_tokens == null || _pointer >= _tokens.Length)
                {
                    _tokens = NextLine().Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    _pointer = 0;
                }
                return _tokens[_pointer++];
            }
            catch (Exception)
            {
                return null;
            }
        }

        public bool Next<T>(out T ans)
        {
            var str = NextString();
            if (str == null)
            {
                ans = default(T);
                return false;
            }
            ans = (T)Convert.ChangeType(str, typeof(T));
            return true;
        }

        public T[] NextArray<T>(int length)
        {
            var array = new T[length];
            for (var i = 0; i < length; i++)
                if (!Next(out array[i]))
                    return null;
            return array;
        }

        public T[,] NextArray<T>(int length, int width)
        {
            var array = new T[length, width];
            for (var i = 0; i < length; i++)
                for (var j = 0; j < width; j++)
                    if (!Next(out array[i, j]))
                        return null;
            return array;
        }

        public void Dispose()
        {
            InputStream.Close();
        }
    }

    public class OutStream : IDisposable
    {
        protected readonly TextWriter OutputStream;

        private OutStream(TextWriter outputStream)
        {
            OutputStream = outputStream;
        }

        public static OutStream FromString(System.Text.StringBuilder strB)
        {
            return new OutStream(new StringWriter(strB));
        }

        public static OutStream FromFile(string str)
        {
            return new OutStream(new StreamWriter(str));
        }

        public static OutStream FromConsole()
        {
            return new OutStream(Console.Out);
        }

        public void Print(string format, params object[] args)
        {
            OutputStream.Write(format, args);
        }

        public void PrintLine(string format, params object[] args)
        {
            Print(format, args);
            OutputStream.WriteLine();
        }

        public void PrintLine()
        {
            OutputStream.WriteLine();
        }

        public void Print<T>(T o)
        {
            OutputStream.Write(o);
        }

        public void PrintLine<T>(T o)
        {
            OutputStream.WriteLine(o);
        }

        public void PrintArray<T>(IList<T> a, string between = " ", string after = "\n", bool printCount = false)
        {
            if (printCount)
                PrintLine(a.Count);
            for (var i = 0; i < a.Count; i++)
                Print("{0}{1}", a[i], i == a.Count - 1 ? after : between);
        }

        public void Dispose()
        {
            OutputStream.Close();
        }
    }

    public abstract class SolutionBase : IDisposable
    {
        private InStream _in;
        private OutStream _out;

        protected SolutionBase()
        {
            //System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            _in = InStream.FromConsole();
            _out = OutStream.FromConsole();
        }

        protected string NextLine()
        {
            return _in.NextLine();
        }

        protected bool Next<T>(out T ans)
        {
            return _in.Next(out ans);
        }

        protected T[] NextArray<T>(int length)
        {
            return _in.NextArray<T>(length);
        }

        protected T[,] NextArray<T>(int length, int width)
        {
            return _in.NextArray<T>(length, width);
        }

        protected void PrintArray<T>(IList<T> a, string between = " ", string after = "\n", bool printCount = false)
        {
            _out.PrintArray(a, between, after, printCount);
        }

        public void Print(string format, params object[] args)
        {
            _out.Print(format, args);
        }

        public void PrintLine(string format, params object[] args)
        {
            _out.PrintLine(format, args);
        }

        public void PrintLine()
        {
            _out.PrintLine();
        }

        public void Print<T>(T o)
        {
            _out.Print(o);
        }

        public void PrintLine<T>(T o)
        {
            _out.PrintLine(o);
        }

        public void Dispose()
        {
            _in.Dispose();
            _out.Dispose();
        }

        public void Freopen(string path, FileAccess access)
        {
            switch (access)
            {
                case FileAccess.Read:
                    _in.Dispose();
                    _in = InStream.FromFile(path);
                    break;
                case FileAccess.Write:
                    _out.Dispose();
                    _out = OutStream.FromFile(path);
                    break;
            }
        }

        protected abstract void Solve();

        public static void Main()
        {
            using (var p = new Solution()) p.Solve();
        }
    }
}


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

namespace mailru2018
{
  class MainClass
  {
    class Box
    {
      public int pos;
      public int candy;
      public int color;
    }

    static int n, s, k;
    static Box[] r;

    static int[,] dp;

    static int find(int at, int candy)
    {
      if (candy >= k)
        return 0;

      if (dp[at, candy] != -1)
        return dp[at, candy];

      int result = int.MaxValue;

      for (int i = at + 1; i < n; ++i)
      {
        if (r[i].color != r[at].color && r[i].candy > r[at].candy)
        {
          int v = find(i, candy + r[i].candy);
          if (v != int.MaxValue)
            result = Math.Min(result, v + Math.Abs(r[at].pos - r[i].pos));
        }
      }

      dp[at, candy] = result;
      return result;
    }

    public static void Main(string[] args)
    {
      //var line = Array.ConvertAll("5 3 10".Split(' '), int.Parse);
      var line = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
      n = line[0];
      s = line[1] - 1;
      k = line[2];

      r = new Box[n];
      //line = Array.ConvertAll("1 2 3 4 5".Split(' '), int.Parse);
      line = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
      //var color = "RGBRR";
      var color = Console.ReadLine();

      for (int i = 0; i < n; ++i)
      {
        var box = new Box();
        box.pos = i;
        box.candy = line[i];
        box.color = color[i];
        r[i] = box;
      }

      Array.Sort(r, (x, y) => {
        return x.candy - y.candy;
      });

      dp = new int[n, 2018];
      for (int i = 0; i < n; ++i)
        for (int j = 0; j < 2018; ++j)
          dp[i, j] = -1;

      int result = int.MaxValue;
      for (int i = 0; i < n; ++i)
      {
        var v = find(i, r[i].candy);

        if (v != int.MaxValue)
          result = Math.Min(result, v + Math.Abs(s - r[i].pos));
      }

      if (result == int.MaxValue)
        result = -1;

      Console.WriteLine(result);
    }
  }
}