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)

using Yorukatsu027.Questions;
using Yorukatsu027.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Yorukatsu027.Questions
{
    /// <summary>
    /// ABC095 D
    /// </summary>
    public class QuestionE : AtCoderQuestionBase
    {
        public override IEnumerable<object> Solve(TextReader inputStream)
        {
            var nc = inputStream.ReadLongArray();
            int n = (int)nc[0];
            var c = nc[1];

            var sushis = new Sushi[n];
            for (int i = 0; i < n; i++)
            {
                var xv = inputStream.ReadLongArray();
                sushis[i] = new Sushi(xv[0], xv[1]);
            }

            var calorieClockwise = new long[n + 1];
            var calorieCounterClockwise = new long[n + 1];
            var calorieClockwiseReturn = new long[n + 1];
            var calorieCounterClockwiseReturn = new long[n + 1];

            long totalSushiCalorie = 0L;
            for (int i = 0; i < n; i++)
            {
                var sushi = sushis[i];
                totalSushiCalorie += sushi.Calorie;
                calorieClockwise[i + 1] = totalSushiCalorie - sushi.Position;
                calorieClockwiseReturn[i + 1] = totalSushiCalorie - 2 * sushi.Position;
            }

            totalSushiCalorie = 0;
            for (int i = n - 1; i >= 0; i--)
            {
                var sushi = sushis[i];
                totalSushiCalorie += sushi.Calorie;
                calorieCounterClockwise[i] = totalSushiCalorie - (c - sushi.Position);
                calorieCounterClockwiseReturn[i] = totalSushiCalorie - 2 * (c - sushi.Position);
            }

            var calorieClockwiseSeg = new SegmentTree<long>(calorieClockwise, (a, b) => Math.Max(a, b), long.MinValue);
            var calorieCounterClockwiseSeg = new SegmentTree<long>(calorieCounterClockwise, (a, b) => Math.Max(a, b), long.MinValue);
            var calorieClockwiseReturnSeg = new SegmentTree<long>(calorieClockwiseReturn, (a, b) => Math.Max(a, b), long.MinValue);
            var calorieCounterClockwiseReturnSeg = new SegmentTree<long>(calorieCounterClockwiseReturn, (a, b) => Math.Max(a, b), long.MinValue);

            var maxCalorie = long.MinValue;
            for (int i = 0; i <= n; i++)
            {
                maxCalorie = Math.Max(maxCalorie, calorieClockwiseSeg.Query(0, i + 1) + calorieCounterClockwiseReturnSeg.Query(i, calorieCounterClockwiseReturnSeg.Length + 1));
                maxCalorie = Math.Max(maxCalorie, calorieClockwiseReturnSeg.Query(0, i + 1) + calorieCounterClockwiseSeg.Query(i, calorieCounterClockwiseSeg.Length + 1));
            }

            yield return maxCalorie;
        }
    }

    struct Sushi
    {
        public long Position { get; }
        public long Calorie { get; }

        public Sushi(long position, long calorie)
        {
            Position = position;
            Calorie = calorie;
        }

        public override string ToString() => $"Position:{Position}, Calorie:{Calorie}";
    }

    public class SegmentTree<T> : IEnumerable<T>
    {
        private readonly T[] _data;
        private readonly T _identityElement;
        private readonly Func<T, T, T> _queryOperation;

        private readonly int _leafOffset;   // n - 1
        private readonly int _leafLength;   // n (= 2^k)

        public int Length { get; }          // 実データ長

        public SegmentTree(ICollection<T> data, Func<T, T, T> queryOperation, T identityElement)
        {
            Length = data.Count;
            _leafLength = GetMinimumPow2(data.Count);
            _leafOffset = _leafLength - 1;
            _data = new T[_leafOffset + _leafLength];
            _queryOperation = queryOperation;
            _identityElement = identityElement;

            data.CopyTo(_data, _leafOffset);
            BuildTree();
        }

        public T this[int index]
        {
            set
            {
                index += _leafOffset;
                _data[index] = value;
                while (index > 0)
                {
                    // 一つ上の親の更新
                    index = (index - 1) / 2;
                    _data[index] = _queryOperation(_data[index * 2 + 1], _data[index * 2 + 2]);
                }
            }
        }

        public T Query(int begin, int end) => Query(begin, end, 0, 0, _leafLength);

        private T Query(int begin, int end, int index, int left, int right)
        {
            if (right <= begin || end <= left)      // 範囲外
            {
                return _identityElement;
            }
            else if (begin <= left && right <= end) // 全部含まれる
            {
                return _data[index];
            }
            else    // 一部だけ含まれる
            {
                var leftValue = Query(begin, end, index * 2 + 1, left, (left + right) / 2);     // 左の子
                var rightValue = Query(begin, end, index * 2 + 2, (left + right) / 2, right);   // 右の子
                return _queryOperation(leftValue, rightValue);
            }
        }

        private void BuildTree()
        {
            for (int i = _leafLength + Length; i < _data.Length; i++)
            {
                _data[i] = _identityElement;
            }

            for (int i = _leafLength - 2; i >= 0; i--)  // 葉の親から順番に一つずつ上がっていく
            {
                _data[i] = _queryOperation(_data[2 * i + 1], _data[2 * i + 2]); // f(left, right)
            }
        }

        private int GetMinimumPow2(int n)
        {
            var p = 1;
            while (p < n)
            {
                p *= 2;
            }
            return p;
        }

        public IEnumerator<T> GetEnumerator()
        {
            var upperIndex = _leafOffset + Length;
            for (int i = _leafOffset; i < upperIndex; i++)
            {
                yield return _data[i];
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
    }

}


namespace Yorukatsu027
{
    class Program
    {
        static void Main(string[] args)
        {
            IAtCoderQuestion question = new QuestionE();    // 問題に合わせて書き換え
            var answers = question.Solve(Console.In);
            foreach (var answer in answers)
            {
                Console.WriteLine(answer);
            }
        }
    }
}

#region Base Classes

namespace Yorukatsu027.Questions
{

    public interface IAtCoderQuestion
    {
        IEnumerable<object> Solve(string input);
        IEnumerable<object> Solve(TextReader inputStream);
    }

    public abstract class AtCoderQuestionBase : IAtCoderQuestion
    {
        public IEnumerable<object> Solve(string input)
        {
            var stream = new MemoryStream(Encoding.Unicode.GetBytes(input));
            var reader = new StreamReader(stream, Encoding.Unicode);

            return Solve(reader);
        }

        public abstract IEnumerable<object> Solve(TextReader inputStream);
    }

}

#endregion

#region Extensions

namespace Yorukatsu027.Extensions
{
    internal static class TextReaderExtensions
    {
        internal static int ReadInt(this TextReader reader) => int.Parse(ReadString(reader));
        internal static long ReadLong(this TextReader reader) => long.Parse(ReadString(reader));
        internal static double ReadDouble(this TextReader reader) => double.Parse(ReadString(reader));
        internal static string ReadString(this TextReader reader) => reader.ReadLine();

        internal static int[] ReadIntArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(int.Parse).ToArray();
        internal static long[] ReadLongArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(long.Parse).ToArray();
        internal static double[] ReadDoubleArray(this TextReader reader, char separator = ' ') => ReadStringArray(reader, separator).Select(double.Parse).ToArray();
        internal static string[] ReadStringArray(this TextReader reader, char separator = ' ') => reader.ReadLine().Split(separator);
    }
}

#endregion