Problem:
Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.

Solution in C# (Mono 4.6.2.0) (judge verdict: Accepted)

// ReSharper disable ArrangeTypeMemberModifiers
// ReSharper disable ConvertIfStatementToSwitchStatement
// ReSharper disable FunctionRecursiveOnAllPaths
// ReSharper disable InconsistentNaming
// ReSharper disable InlineOutVariableDeclaration
// ReSharper disable InvertIf
// ReSharper disable JoinDeclarationAndInitializer
// ReSharper disable MemberCanBeMadeStatic.Global
// ReSharper disable MemberCanBeMadeStatic.Local
// ReSharper disable NonReadonlyMemberInGetHashCode
// ReSharper disable PossibleNullReferenceException
// ReSharper disable RedundantUsingDirective
// ReSharper disable SuggestVarOrType_BuiltInTypes
// ReSharper disable SuggestVarOrType_Elsewhere
// ReSharper disable TailRecursiveCall
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
// ReSharper disable UseObjectOrCollectionInitializert

#if true && UTAKA_LOCAL

//#if false
#define UTAKA_DEBUG
#endif

//#define TOPCODER

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using static UtakaApp.Util;

namespace UtakaApp
{
    public partial class Program
    {
        public const string SiteName    = "AtCoder";
        public const string ContestName = "arc096";
        public const string ProblemName = "B";

        public void Solve()
        {
            int  N = cin.ReadInt;
            long C = cin.ReadLong;

            long[] X = new long[N];
            long[] V = new long[N];

            for (int i = 0; i < N; i++)
            {
                X[i] = cin.ReadLong;
                V[i] = cin.ReadLong;
            }

            long[] l1Max = new long[N + 1];
            long[] l2Max = new long[N + 1];
            long[] r1Max = new long[N + 1];
            long[] r2Max = new long[N + 1];

            long sum = 0;

            for (int i = 0; i < N; i++)
            {
                sum += V[i];
                l1Max[i + 1] = Math.Max(l1Max[i], sum - X[i]);
                l2Max[i + 1] = Math.Max(l2Max[i], sum - X[i] * 2);
            }

            sum = 0;

            for (int i = N - 1; i >= 0; i--)
            {
                sum += V[i];
                r1Max[i] = Math.Max(r1Max[i + 1], sum - (C - X[i]));
                r2Max[i] = Math.Max(r2Max[i + 1], sum - (C - X[i]) * 2);
            }

            long ans = 0;

            for (int i = 0; i <= N; i++)
            {
                ans = Math.Max(ans, Math.Max(l2Max[i] + r1Max[i], l1Max[i] + r2Max[i]));
            }
            
            cou.WriteLine(ans);
        }
    }


//=========================================================================================
// Debug IO
//=========================================================================================

    public partial class Program
    {
        //=========================================================================================
        // Main
        //=========================================================================================

        private readonly ConsoleInput cin;
        private readonly IConsole     cou;

        public Program(ConsoleInput cin, IConsole cou)
        {
            this.cin = cin;
            this.cou = cou;
        }

#if !TOPCODER
        public static void Main(string[] args)
        {
#if UTAKA_LOCAL
//#if false
            new TestCaseCheckerForAtCoder().TestProblems();
#else
            var cin = new ConsoleInput(System.Console.In);
            var console = new MyConsole();
            new Program(cin, console).Solve();
            console.Flush();
#endif
        }
#endif

        public void WriteEnumerable<T>(IEnumerable<T> A, string delimiter = " ")
        {
            if (!A.Any())
            {
                return;
            }

            var sb = new StringBuilder();
            foreach (T v in A)
            {
                sb.Append(v);
                sb.Append(delimiter);
            }

            if (sb.Length > 0)
            {
                sb.Length--;
            }

            cou.WriteLine(sb.ToString());
        }
    }

    public static class Util
    {
        public static int LowerBound<T>(T[] arr, int start, int end, T value, IComparer<T> comparer)
        {
            int low  = start;
            int high = end;
            while (low < high)
            {
                var mid = ((high - low) >> 1) + low;
                if (comparer.Compare(arr[mid], value) < 0)
                    low = mid + 1;
                else
                    high = mid;
            }

            return low;
        }

        public static int LowerBound<T>(T[] arr, T value) where T : IComparable
        {
            return LowerBound(arr, 0, arr.Length, value, Comparer<T>.Default);
        }

        public static int UpperBound<T>(T[] arr, int start, int end, T value, IComparer<T> comparer)
        {
            int low  = start;
            int high = end;
            while (low < high)
            {
                var mid = ((high - low) >> 1) + low;
                if (comparer.Compare(arr[mid], value) <= 0)
                    low = mid + 1;
                else
                    high = mid;
            }

            return low;
        }

        public static int UpperBound<T>(T[] arr, T value)
        {
            return UpperBound(arr, 0, arr.Length, value, Comparer<T>.Default);
        }

        public static int UpperBound<T>(List<T> list, int start, int end, T value, IComparer<T> comparer)
        {
            int low  = start;
            int high = end;
            while (low < high)
            {
                var mid = ((high - low) >> 1) + low;
                if (comparer.Compare(list[mid], value) <= 0)
                    low = mid + 1;
                else
                    high = mid;
            }

            return low;
        }

        public static int UpperBound<T>(List<T> list, T value)
        {
            return UpperBound(list, 0, list.Count, value, Comparer<T>.Default);
        }

        public static T[] Array1D<T>(int a, T defaultValue)
            where T : struct
        {
            var ret = new T[a];
            for (int i = 0; i < a; i++)
            {
                ret[i] = defaultValue;
            }

            return ret;
        }

        public static T[] Array1D<T>(int a)
            where T : struct
        {
            var ret = new T[a];
            return ret;
        }

        /// <summary>
        /// 要素数 (a, b) の、defaultValue で満たされた配列を作成します。
        /// </summary>
        /// <typeparam name="T">配列の型</typeparam>
        /// <param name="a">1次元の要素数</param>
        /// <param name="b">2次元の要素数</param>
        /// <param name="defaultValue">デフォルト値</param>
        /// <returns>指定した条件で初期化された配列</returns>
        public static T[,] Array2D<T>(int a, int b, T defaultValue)
            where T : struct
        {
            var ret = new T[a, b];
            for (int i = 0; i < a; i++)
            {
                for (int j = 0; j < b; j++)
                {
                    ret[i, j] = defaultValue;
                }
            }

            return ret;
        }

        public static T[,,] Array3D<T>(int a, int b, int c, T defaultValue)
            where T : struct
        {
            T[,,] ret = new T[a, b, c];

            for (int i = 0; i < a; i++)
            {
                for (int j = 0; j < b; j++)
                {
                    for (int k = 0; k < c; k++)
                    {
                        ret[i, j, k] = defaultValue;
                    }
                }
            }

            return ret;
        }

        /// <summary>
        /// 要素数 (a, b) の、defaultValue で満たされたJag配列を作成します。
        /// </summary>
        /// <typeparam name="T">配列の型</typeparam>
        /// <param name="a">1次元の要素数</param>
        /// <param name="b">2次元の要素数</param>
        /// <param name="defaultValue">デフォルト値</param>
        /// <returns>指定した条件で初期化された配列</returns>
        public static T[][] JagArray2D<T>(int a, int b, T defaultValue)
            where T : struct
        {
            var ret = new T[a][];
            for (int i = 0; i < a; i++)
            {
                var row = new T[b];
                ret[i] = row;

                for (int j = 0; j < b; j++)
                {
                    row[j] = defaultValue;
                }
            }

            return ret;
        }

        /// <summary>
        /// 要素数 (a, b) のdefault値で満たされたJag配列を作成します。
        /// </summary>
        /// <typeparam name="T">配列の型</typeparam>
        /// <param name="a">1次元の要素数</param>
        /// <param name="b">2次元の要素数</param>
        /// <returns>初期化された配列</returns>
        public static T[][] JagArray2D<T>(int a, int b)
            where T : struct
        {
            var ret = new T[a][];
            for (int i = 0; i < a; i++)
            {
                ret[i] = new T[b];
            }

            return ret;
        }

        public static T[][][] JagArray3D<T>(int a, int b, int c, T defaultValue)
            where T : struct
        {
            var ret = new T[a][][];
            for (int i = 0; i < a; i++)
            {
                T[][] aRow = new T[b][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[] bRow = new T[c];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        bRow[k] = defaultValue;
                    }
                }
            }

            return ret;
        }

        public static T[][][] JagArray3D<T>(int a, int b, int c)
            where T : struct
        {
            var ret = new T[a][][];
            for (int i = 0; i < a; i++)
            {
                T[][] aRow = new T[b][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[] bRow = new T[c];
                    aRow[j] = bRow;
                }
            }

            return ret;
        }

        public static T[][][][] JagArray4D<T>(int a, int b, int c, int d, T defaultValue)
            where T : struct
        {
            var ret = new T[a][][][];
            for (int i = 0; i < a; i++)
            {
                T[][][] aRow = new T[b][][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[][] bRow = new T[c][];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        T[] cRow = new T[d];
                        bRow[k] = cRow;

                        for (int l = 0; l < d; l++)
                        {
                            cRow[l] = defaultValue;
                        }
                    }
                }
            }

            return ret;
        }

        public static T[][][][] JagArray4D<T>(int a, int b, int c, int d)
            where T : struct
        {
            var ret = new T[a][][][];
            for (int i = 0; i < a; i++)
            {
                T[][][] aRow = new T[b][][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[][] bRow = new T[c][];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        T[] cRow = new T[d];
                        bRow[k] = cRow;
                    }
                }
            }

            return ret;
        }

        public static T[][][][][] JagArray5D<T>(int a, int b, int c, int d, int e, T defaultValue)
            where T : struct
        {
            var ret = new T[a][][][][];
            for (int i = 0; i < a; i++)
            {
                T[][][][] aRow = new T[b][][][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[][][] bRow = new T[c][][];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        T[][] cRow = new T[d][];
                        bRow[k] = cRow;

                        for (int l = 0; l < d; l++)
                        {
                            T[] dRow = new T[e];
                            cRow[l] = dRow;

                            for (int m = 0; m < e; m++)
                            {
                                dRow[m] = defaultValue;
                            }
                        }
                    }
                }
            }

            return ret;
        }

        public static T[][][][][] JagArray5D<T>(int a, int b, int c, int d, int e)
            where T : struct
        {
            var ret = new T[a][][][][];
            for (int i = 0; i < a; i++)
            {
                T[][][][] aRow = new T[b][][][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[][][] bRow = new T[c][][];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        T[][] cRow = new T[d][];
                        bRow[k] = cRow;

                        for (int l = 0; l < d; l++)
                        {
                            T[] dRow = new T[e];
                            cRow[l] = dRow;
                        }
                    }
                }
            }

            return ret;
        }

        /// <summary>
        /// ジャグ配列をコピーして返す。
        /// </summary>
        public static T[][] CopyJagArray2D<T>(T[][] source)
            where T : struct
        {
            int   len  = source.Length;
            T[][] dest = new T[len][];

            for (int i = 0; i < len; i++)
            {
                T[] inner       = source[i];
                int innerLength = inner.Length;
                T[] newer       = new T[innerLength];
                Array.Copy(inner, newer, innerLength);
                dest[i] = newer;
            }

            return dest;
        }
    }

    public static class UtakaExtentions
    {
        /// <summary>
        /// IList<T>をコピーします
        /// </summary>
        public static T[] Copy<T>(this IList<T> a)
        {
            T[] ret = new T[a.Count];

            for (int i = 0; i < a.Count; i++) ret[i] = a[i];

            return ret;
        }

        /// <summary>
        /// 2次元ジャグ配列をコピーして返す。
        /// </summary>
        public static T[][] Copy<T>(this T[][] source)
            where T : struct
        {
            int   len  = source.Length;
            T[][] dest = new T[len][];

            for (int i = 0; i < len; i++)
            {
                T[] inner       = source[i];
                int innerLength = inner.Length;
                T[] newer       = new T[innerLength];
                Array.Copy(inner, newer, innerLength);
                dest[i] = newer;
            }

            return dest;
        }

        /// <summary>
        /// 昇順にソートされたlong配列で、threshold以上の値をカウントする
        /// </summary>
        public static int LargerCount(this long[] a, long threshold)
        {
            int ng = -1;
            int ok = a.Length;

            while (Math.Abs(ng - ok) > 1)
            {
                int mid = (ok + ng) / 2;
                if (threshold <= a[mid])
                {
                    ok = mid;
                }
                else
                {
                    ng = mid;
                }
            }

            return a.Length - ok;
        }
    }

    public class IntLargeComparer : IComparer<int>
    {
        public static IntLargeComparer Instance = new IntLargeComparer();

        public int Compare(int x, int y)
        {
            return y - x;
        }
    }

    public class LongLargeComparer : IComparer<long>
    {
        public static LongLargeComparer Instance = new LongLargeComparer();

        public int Compare(long x, long y)
        {
            if (x > y) return -1;
            if (x < y) return 1;
            return 0;
        }
    }

    public class ConsoleInput
    {
        private readonly char          _separator = ' ';
        private readonly TextReader    _stream;
        private readonly Queue<string> inputStream;

        public ConsoleInput(TextReader stream, char separator = ' ')
        {
            _separator  = separator;
            _stream     = stream;
            inputStream = new Queue<string>();
        }

        public string Read
        {
            get
            {
                if (inputStream.Count != 0)
                {
                    return inputStream.Dequeue();
                }

                var tmp = _stream.ReadLine().Split(_separator);
                for (var i = 0; i < tmp.Length; ++i)
                {
                    inputStream.Enqueue(tmp[i]);
                }

                return inputStream.Dequeue();
            }
        }

        public string ReadLine   => _stream.ReadLine();
        public int    ReadInt    => int.Parse(Read);
        public long   ReadLong   => long.Parse(Read);
        public double ReadDouble => double.Parse(Read);

        public string[] ReadStrArray(long N)
        {
            var ret = new string[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = Read;
            }

            return ret;
        }

        public int[] ReadIntArray(long N)
        {
            var ret = new int[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = ReadInt;
            }

            return ret;
        }

        public int[] ReadIntArrayMinus1(long N)
        {
            var ret = new int[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = ReadInt - 1;
            }

            return ret;
        }

        public long[] ReadLongArray(long N)
        {
            var ret = new long[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = ReadLong;
            }

            return ret;
        }
    }

    public interface IConsole
    {
        void Flush();
        void Write(object obj);
        void Write(string str);
        void WriteLine(object obj);
        void WriteLine(string str);
        void WriteLine();
    }

    public class MyConsole : IConsole
    {
        public MyConsole()
        {
            var sw = new StreamWriter(Console.OpenStandardOutput()) {AutoFlush = false};
            Console.SetOut(sw);
        }

        public void Flush()
        {
            Console.Out.Flush();
        }

        public void Write(object obj)
        {
            Write(obj.ToString());
        }

        public void Write(string str)
        {
            Console.Write(str);
        }

        public void WriteLine(object obj)
        {
            WriteLine(obj.ToString());
        }

        public void WriteLine(string str)
        {
            Console.WriteLine(str);
        }

        public void WriteLine()
        {
            Console.WriteLine();
        }
    }

#if UTAKA_LOCAL

    public class DebugConsole : IConsole
    {
        private readonly StringBuilder mSb;

        public DebugConsole()
        {
            mSb = new StringBuilder();
        }

        public void Flush()
        {
            // 何もしない
        }

        public void Write(object obj)
        {
            Write(obj.ToString());
        }

        public void Write(string str)
        {
            mSb.Append(str);
        }

        public void WriteLine(object obj)
        {
            WriteLine(obj.ToString());
        }

        public void WriteLine(string str)
        {
            mSb.AppendLine(str);
        }

        public void WriteLine()
        {
            mSb.AppendLine();
        }

        public string GetAllOutput()
        {
            return mSb.ToString();
        }
    }

#endif

#if UTAKA_LOCAL

    public class TestCaseCheckerForAtCoder
    {
        private string GetDirectoryPath()
        {
            var problemPart = string.IsNullOrEmpty(Program.ProblemName)
                ? ""
                : $"/{Program.ProblemName}";

            return
                $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/AlgorithmPrac/{Program.SiteName}/{Program.ContestName}{problemPart}";
        }

        private string GetInputFilePath(int testCaseNumber)
        {
            return $"{GetDirectoryPath()}/sample-{testCaseNumber}.in";
        }

        private string GetOutputFilePath(int testCaseNumber)
        {
            return $"{GetDirectoryPath()}/sample-{testCaseNumber}.out";
        }

        public bool TestProblem(int testCaseNumber)
        {
            var inputFilePath  = GetInputFilePath(testCaseNumber);
            var outputFilePath = GetOutputFilePath(testCaseNumber);

            TextReader inputStream = new StreamReader(inputFilePath);
            var        cin         = new ConsoleInput(inputStream);

            var debugConsoleWriter = new DebugConsole();

            new Program(cin, debugConsoleWriter).Solve();

            var output = debugConsoleWriter.GetAllOutput();

            TextReader outputStream = new StreamReader(outputFilePath);
            var        outputAnswer = outputStream.ReadToEnd();

            Dbg.WriteLine(output);
            Dbg.WriteLine(outputAnswer);

            var isCorrect = output == outputAnswer;

            return isCorrect;
        }

        public void TestProblems(int targetTestCaseNumber = -1)
        {
            if (targetTestCaseNumber >= 0)
            {
                Console.WriteLine($"!!!!!!!!!!!! Check TestCase {targetTestCaseNumber} !!!!!!!!!!");
            }

            bool isSuccessAll = true;

            int testCaseNumber = 0;
            while (true)
            {
                testCaseNumber++;

                bool foundTargetTest = targetTestCaseNumber == testCaseNumber;

                if (targetTestCaseNumber >= 0 && !foundTargetTest)
                {
                    continue;
                }

                var inputFileName = GetInputFilePath(testCaseNumber);
                if (!File.Exists(inputFileName))
                {
                    break;
                }

                Console.WriteLine($"TestCase {testCaseNumber} =====================================================");

                var result = TestProblem(testCaseNumber);

                if (result)
                {
                    Console.WriteLine("Success");
                }
                else
                {
                    isSuccessAll = false;
                    Console.WriteLine("Failure *****");
                }

                if (foundTargetTest)
                {
                    break;
                }
            }

            if (isSuccessAll)
            {
                Console.WriteLine("!!!!!!!!! All Success !!!!!!!!!");
            }
        }
    }

#endif

    public static class Dbg
    {
        [Conditional("UTAKA_DEBUG")]
        public static void WriteLine(string str)
        {
            Console.WriteLine(str);
        }

        [Conditional("UTAKA_DEBUG")]
        public static void WriteLine()
        {
            Console.WriteLine();
        }

        [Conditional("UTAKA_DEBUG")]
        public static void Write(string str)
        {
            Console.Write(str);
        }
    }
}