Problem:
C: Shuttle Run
Story
University H has a unique physical fitness test program, aiming to grow the mindset of students.
Among the items in the program, shuttle run is well-known as especially eccentric one. Surprisingly, there are yokans (sweet beans jellies) on a route of the shuttle run. Greedy Homura-chan would like to challenge to eat all the yokans. And lazy Homura-chan wants to make the distance she would run as short as possible. For her, you decided to write a program to compute the minimum distance she would run required to eat all the yokans.
Problem Statement
At the beginning of a shuttle run, Homura-chan is at
0
in a positive direction on a number line. During the shuttle run, Homura-chan repeats the following moves:
Move in a positive direction until reaching
M
.
When reaching
M
, change the direction to negative.
Move in a negative direction until reaching
0
.
When reaching
0
, change the direction to positive.
During the moves, Homura-chan also eats yokans on the number line. There are
N
yokans on the number line. Initially, the
i
-th yokan, whose length is
R_i - L_i
, is at an interval
[L_i, R_i]
on the number line. When Homura-chan reaches
L_i
in a positive direction (or
R_i
in a negative direction), she can start eating the
i
-th yokan from
L_i
to
R_i
(or from
R_i
to
L_i
), and then the
i
-th yokan  disappears. Unfortunately, Homura-chan has only one mouth. So she cannot eat two yokans at the same moment, including even when she starts eating and finishes eating (See the example below). Also, note that she cannot stop eating in the middle of yokan and has to continue eating until she reaches the other end of the yokan she starts eating; it's her belief.
Calculate the minimum distance Homura-chan runs to finish eating all the yokans. The shuttle run never ends until Homura-chan eats all the yokans.
Input
N
M
L_1
R_1
:
L_N
R_N
The first line contains two integers
N
and
M
. The following
N
lines represent the information of yokan, where the
i
-th of them contains two integers
L_i
and
R_i
corresponding to the interval
[L_i, R_i]
the
i
-th yokan is.
Constraints
1 \leq N \leq 2 \times 10^5
3 \leq M \leq 10^9
0 < L_i < R_i < M
Inputs consist only of integers.
Output
Output the minimum distance Homura-chan runs to eat all the given yokan in a line.
Sample Input 1
1 3
1 2
Output for Sample Input 1
2
Sample Input 2
2 5
1 2
2 4
Output for Sample Input 2
8
Note that when Homura-chan is at the coordinate
2
, she cannot eat the first and second yokan at the same time.

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;

bool chmin(auto &a, auto b) { return a > b ? a = b, true : false; }
bool chmax(auto &a, auto b) { return a < b ? a = b, true : false; }

template <typename Monoid>
struct segtree {
    using M = Monoid;
    using S = typename M::S;
    segtree() : segtree(0) {}
    segtree(int _n) : segtree(vector<S>(_n, M::e())) {}
    segtree(const vector<S> &v) : n(v.size()) {
        log = 1;
        while ((1 << log) < n) log++;
        sz = 1 << log;
        d = vector<S>(2 * sz, M::e());
        for (int i = 0; i < n; i++) d[i + sz] = v[i];
        for (int i = sz - 1; i >= 1; i--) update(i);
    }
    void set(int p, const S &x) {
        assert(0 <= p && p < n);
        p += sz;
        d[p] = x;
        for (int i = 1; i <= log; i++) update(p >> i);
    }
    S get(int p) const {
        assert(0 <= p && p < n);
        return d[p + sz];
    }
    S prod(int l, int r) const {
        assert(0 <= l && l <= r && r <= n);
        l += sz;
        r += sz;
        S pl = M::e(), pr = M::e();
        while (l < r) {
            if (l & 1) pl = M::op(pl, d[l++]);
            if (r & 1) pr = M::op(d[--r], pr);
            l >>= 1;
            r >>= 1;
        }
        return M::op(pl, pr);
    }
    S all_prod() const { return d[1]; }
    template<typename C>
    int max_right(int l, const C &check) const {
        assert(0 <= l && l <= n);
        assert(check(M::e()));
        if (l == n) return l;
        l += sz;
        S p = M::e();
        do {
            while (!(l & 1)) l >>= 1;
            S np = M::op(p, d[l]);
            if (!check(np)) {
                while (l < sz) {
                    l <<= 1;
                    np = M::op(p, d[l]);
                    if (check(np)) {
                        p = np;
                        l++;
                    }
                }
                return l - sz;
            }
            p = np;
            l++;
        } while ((l & -l) != l);
        return n;
    }
    template<typename C>
    int max_right(const C &check) const {
        return max_right(0, check);
    }
    template<typename C>
    int min_left(int r, const C &check) const {
        assert(0 <= r && r <= n);
        assert(check(M::e()));
        if (r == 0) return r;
        r += sz;
        S p = M::e();
        do {
            r--;
            while (r > 1 && r & 1) r >>= 1;
            S np = M::op(d[r], p);
            if (!check(np)) {
                while (r < sz) {
                    (r <<= 1)++;
                    np = M::op(d[r], p);
                    if (check(np)) {
                        p = np;
                        r--;
                    }
                }
                return r + 1 - sz;
            }
            p = np;
        } while ((r & -r) != r);
        return 0;
    }
    template<typename C>
    int min_left(const C &check) const {
        return min_left(n, check);
    }
private:
    int n, log, sz;
    vector<S> d;
    void update(int p) {
        d[p] = M::op(d[2 * p], d[2 * p + 1]);
    }
};

struct Monoid {
    using S = pair<int, int>;
    static S op(S a, S b) { return min(a, b); }
    static S e() { return {1 << 30, -1}; }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int N, M;
    cin >> N >> M;
    vector<int> L(N), R(N), B;
    for (int i = 0; i < N; i++) {
        cin >> L[i] >> R[i];
        B.push_back(L[i]);
        B.push_back(R[i]);
    }
    sort(B.begin(), B.end());
    B.erase(unique(B.begin(), B.end()), B.end());
    int K = B.size();
    vector<int> S(K + 1);
    for (int i = 0; i < N; i++) {
        int l = lower_bound(B.begin(), B.end(), L[i]) - B.begin();
        int r = lower_bound(B.begin(), B.end(), R[i]) - B.begin();
        S[l]++, S[r + 1]--;
    }
    for (int i = 0; i < K; i++) S[i + 1] += S[i];
    int T = *max_element(S.begin(), S.end());
    ll ans = (ll)M * T;
    if (T & 1) {
        int R = 0;
        for (int i = 0; i < K; i++) {
            if (S[i] == T) chmax(R, B[i]);
        }
        ans -= M - R;
    } else {
        int L = M;
        for (int i = 0; i < K; i++) {
            if (S[i] == T) chmin(L, B[i]);
        }
        ans -= L;
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 70
memory_kb: 8196
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;

bool chmin(auto &a, auto b) { return a > b ? a = b, true : false; }
bool chmax(auto &a, auto b) { return a < b ? a = b, true : false; }

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int N, M;
    cin >> N >> M;
    using T = tuple<int, int, int>;
    priority_queue<T, vector<T>, greater<T>> q;
    for (int i = 0, L, R; i < N; i++) {
        cin >> L >> R;
        q.emplace(L, 0, i);
        q.emplace(R, 1, i);
    }
    vector<vector<int>> table;
    set<int> id;
    vector<int> inv(N);
    while (q.size()) {
        auto [pos, t, i] = q.top();
        q.pop();
        if (t == 0) {
            if (id.empty()) {
                id.insert(table.size());
                table.emplace_back();
            }
            int j = *id.begin();
            id.erase(id.begin());
            table[j].push_back(pos);
            inv[i] = j;
        } else {
            int j = inv[i];
            table[j].push_back(pos);
            id.insert(j);
        }
    }
    ll ans = (ll)M * table.size();
    if (table.size() & 1) {
        int R = M;
        for (auto V : table) chmin(R, V.back());
        ans -= M - R;
    } else {
        int L = 0;
        for (auto V : table) chmax(L, V.front());
        ans -= L;
    }
    cout << ans << endl;
}
accuracy: 0.058823529411764705
time_ms: 50
memory_kb: 12780
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;

bool chmin(auto &a, auto b) { return a > b ? a = b, true : false; }
bool chmax(auto &a, auto b) { return a < b ? a = b, true : false; }

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int N, M;
    cin >> N >> M;
    using T = tuple<int, int, int>;
    priority_queue<T, vector<T>, greater<T>> q;
    for (int i = 0, L, R; i < N; i++) {
        cin >> L >> R;
        q.emplace(L, 0, i);
        q.emplace(R, 1, i);
    }
    vector<vector<int>> table;
    set<int> id;
    vector<int> inv(N);
    while (q.size()) {
        auto [pos, t, i] = q.top();
        q.pop();
        if (t == 0) {
            if (id.empty()) {
                id.insert(table.size());
                table.emplace_back();
            }
            int j = *id.begin();
            id.erase(id.begin());
            table[j].push_back(pos);
            inv[i] = j;
        } else {
            int j = inv[i];
            table[j].push_back(pos);
            id.erase(j);
        }
    }
    ll ans = (ll)M * table.size();
    if (table.size() & 1) {
        int R = M;
        for (auto V : table) chmin(R, V.back());
        ans -= M - R;
    } else {
        int L = 0;
        for (auto V : table) chmax(L, V.front());
        ans -= L;
    }
    cout << ans << endl;
}
accuracy: 0.058823529411764705
time_ms: 40
memory_kb: 12656
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for(ll i = 0; i < n; ++i)
#define INF 1LL << 60
#define mod 998244353

int main(){
    ll n, m; cin >> n >> m;
    map<ll, ll> imos;
    rep(i, n) {
        ll l, r; cin >> l >> r;
        imos[l - 1] += 0;
        imos[l]++;
        imos[r] += 0;
        imos[r + 1]--;
    }
    ll sum = 0;
    ll ma = 0;
    for(auto& p : imos){
        sum += p.second;
        p.second = sum;
        ma = max(ma, p.second);

        // cout << p.first << ":" << p.second << " ";
    }
    if(ma % 2 == 1){
        ll ans = 0;
        for(auto& p : imos){
            if(p.second == ma){
                ans = p.first;
            }
        }
        cout << m * (ma - 1) + ans << endl;
    }else{
        ll ans = 0;
        for(auto& p : imos){
            if(p.second == ma){
                ans = p.first;
                break;
            }
        }
        cout << m * (ma - 1) + (m - ans) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 53396
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for(ll i = 0; i < (ll)n; ++i)

int main() {
    ll n, m; cin >> n >> m;
	map<ll, ll> imos;

    rep(i, n) {
        ll l, r; cin >> l >> r;
        imos[l-1]+=0;
		imos[l]++;
		imos[r]+=0;
        imos[r + 1]--;
    }
    ll sum = 0;
    ll ma = 0;
    for(auto& p : imos){

        sum += p.second;
        p.second = sum;
        ma = max(ma, p.second);

        //cout << p.first << ":" << p.second << " ";
    }
    //cout << endl;
    if(ma % 2 == 1){
        ll ans = 0;
        for(auto& p : imos){
            if(p.second == ma){
                ans = p.first;
            }
        }
        cout << m * (ma - 1) + ans << endl;
    }else{
        ll ans = 0;
        for(auto& p : imos){
            if(p.second == ma){
                ans = p.first;
                break;
            }
        }
        cout << m * (ma - 1) + (m - ans) << endl;
    }
}
accuracy: 1
time_ms: 400
memory_kb: 53336
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for(ll i = 0; i < (ll)n; ++i)

int main() {
    ll n, m; cin >> n >> m;
    map<ll, ll> imos;
    rep(i, n) {
        ll l, r; cin >> l >> r;
        imos[l - 1]++;
        imos[r]--;
    }
    ll sum = 0;
    ll ma = 0;
    for(auto& p : imos){
        sum += p.second;
        p.second = sum;
        ma = max(ma, p.second);
    }
    if(ma % 2 == 1){
        ll ans = 0;
        for(auto& p : imos){
            if(p.second == ma){
                ans = p.first;
            }
        }
        ans++;
        cout << m * (ma - 1) + ans + 1 << endl;
    }else{
        ll ans = 0;
        for(auto& p : imos){
            if(p.second == ma){
                ans = p.first;
                break;
            }
        }
        cout << m * (ma - 1) + (m - ans - 1) << endl;
    }
}
accuracy: 0.058823529411764705
time_ms: 120
memory_kb: 17468
final_rank: 18

code_snippet: #include <iostream>
#include <iomanip>
#include <cassert>
#include <vector>
#include <algorithm>
#include <utility>
#include <numeric>
#include <set>
// #include "Src/Utility/BinarySearch.hpp"
// #include "Src/Sequence/CompressedSequence.hpp"
// #include "Src/Sequence/RunLengthEncoding.hpp"
// using namespace zawa;
// #include "atcoder/modint"
// using mint = atcoder::modint998244353;
int N, M, L[200020], R[200020];
int main() {
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    std::ios::sync_with_stdio(false);
    std::cin >> N >> M;
    std::vector<std::pair<int, int>> event(2*N);
    for (int i = 0 ; i < N ; i++) {
        std::cin >> L[i] >> R[i];
        R[i]++;
        event[2*i] = {L[i], i+1};
        event[2*i+1] = {R[i], -i};
    }
    std::sort(event.begin(), event.end());
    std::multiset<int> ls, rs;
    long long ans = 0;
    for (int i = 0, j = 0 ; i < 2*N ; i = j) {
        while (j < 2*N and event[i].first == event[j].first and event[j].second <= 0) j++;
        for (int k = i ; k < j ; k++) {
            int id = -event[k].second;
            ls.erase(ls.find(L[id]));
            rs.erase(rs.find(R[id]));
        }
        while (j < 2*N and event[i].first == event[j].first) {
            assert(1 <= event[j].second and event[j].second <= N);
            int id = event[j].second - 1;
            ls.insert(L[id]);
            rs.insert(R[id]);
            j++;
        }
        assert(ls.size() == rs.size());
        int sz = (int)ls.size();
        if (sz) {
            int add = (sz & 1 ? *rs.begin() - 1 : M - *ls.rbegin());
            ans = std::max(ans, (long long)M * (sz - 1) + add);
        }
    }
    std::cout << ans << '\n';
}
accuracy: 1
time_ms: 150
memory_kb: 26784
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll=long long;

/*
    考察
	1点に被っている区間数の最大値をLとして、最低でもL回走らなければならない。

	最後のランが右方向なら、一番右の区間数=Lの点について、終了点が一番左のものを最後に残せば良い。
*/

int main(){
	ll N,M; cin>>N>>M;
	vector<ll> L(N),R(N);
	for(int i=0; i<N; i++) cin>>L[i]>>R[i];

	vector<ll> vals;
	for(int i=0; i<N; i++) vals.push_back(L[i]), vals.push_back(R[i]);
	sort(vals.begin(),vals.end());
	vals.erase(unique(vals.begin(),vals.end()),vals.end());
	auto gt=[&](ll x){return lower_bound(vals.begin(),vals.end(),x)-vals.begin();};
	int wid=vals.size();
	
	vector<int> range(wid+10);
	for(int i=0; i<N; i++) range[gt(L[i])]++, range[gt(R[i])+1]--;
	for(int i=0; i<wid; i++) range[i+1]+=range[i];
	int most=*max_element(range.begin(),range.end());

	int mx=*max_element(range.begin(),range.end());
	vector<int> left(wid,-1),right(wid,1<<30);
	multiset<int> msl={-1},msr={1<<30};
	vector<vector<int>> addl(wid+10),dell(wid+10),addr(wid+10),delr(wid+10);
	for(int i=0; i<N; i++){
		addl[gt(L[i])].push_back(gt(L[i]));
		addr[gt(L[i])].push_back(gt(R[i]));
		dell[gt(R[i])].push_back(gt(L[i]));
		delr[gt(R[i])].push_back(gt(R[i]));
	}
	for(int i=0; i<wid; i++){
		for(int x:addl[i]) msl.insert(x);
		for(int x:addr[i]) msr.insert(x);
		left[i]=*msl.rbegin(); right[i]=*msr.begin();
		for(int x:dell[i]) msl.erase(msl.find(x));
		for(int x:delr[i]) msr.erase(msr.find(x));
	}

	ll ans=M*(most-1);

	if(most%2==1){
		for(int i=wid-1; i>=0; i--){
			if(range[i]==most){
				ans+=vals[right[i]];
				break;
			}
		}
	}
	else{
		for(int i=0; i<wid; i++){
			if(range[i]==most){
				ans+=M-vals[left[i]];
				break;
			}
		}
	}

	cout<<ans<<endl;
}
accuracy: 1
time_ms: 570
memory_kb: 86308
final_rank: 11

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll=long long;

/*
    考察
	1点に被っている区間数の最大値をLとして、最低でもL回走らなければならない。

	最後のランが右方向なら、一番右の区間数=Lの点について、終了点が一番左のものを最後に残せば良い。
*/

int main(){
	ll N,M; cin>>N>>M;
	vector<ll> L(N),R(N);
	for(int i=0; i<N; i++) cin>>L[i]>>R[i];

	vector<ll> vals;
	for(int i=0; i<N; i++) vals.push_back(L[i]), vals.push_back(R[i]);
	sort(vals.begin(),vals.end());
	vals.erase(unique(vals.begin(),vals.end()),vals.end());
	auto gt=[&](ll x){return lower_bound(vals.begin(),vals.end(),x)-vals.begin();};
	int wid=vals.size();
	
	vector<int> range(wid+10);
	for(int i=0; i<N; i++) range[gt(L[i])]++, range[gt(R[i])+1]--;
	for(int i=0; i<wid; i++) range[i+1]+=range[i];
	int most=*max_element(range.begin(),range.end());

	int mx=*max_element(range.begin(),range.end());
	vector<int> left(wid,-1),right(wid,1<<30);
	multiset<int> msl={-1},msr={1<<30};
	vector<vector<int>> addl(wid+10),dell(wid+10),addr(wid+10),delr(wid+10);
	for(int i=0; i<N; i++){
		addl[gt(L[i])].push_back(gt(L[i]));
		addr[gt(L[i])].push_back(gt(R[i]));
		dell[gt(R[i])].push_back(gt(L[i]));
		delr[gt(R[i])].push_back(gt(R[i]));
	}
	for(int i=0; i<wid; i++){
		for(int x:addl[i]) msl.insert(x);
		for(int x:addr[i]) msr.insert(x);
		left[i]=*msl.rbegin(); right[i]=*msr.begin();
		for(int x:dell[i]) msl.erase(msl.find(x));
		for(int x:delr[i]) msr.erase(msr.find(x));
	}

	ll ans=M*(most-1);

	if(most%2==1){
		for(int i=0; i<wid; i++){
			if(range[i]==most){
				ans+=vals[right[i]];
				break;
			}
		}
	}
	else{
		for(int i=wid-1; i>=0; i--){
			if(range[i]==most){
				ans+=M-vals[left[i]];
				break;
			}
		}
	}

	cout<<ans<<endl;
}
accuracy: 0.058823529411764705
time_ms: 270
memory_kb: 49884
final_rank: 20

code_snippet: // (⁠◕⁠ᴗ⁠◕⁠✿⁠)

// #pragma GCC target("avx2")
// #pragma GCC optimize("O3")
// #pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define srep(i, s, n) for (ll i = s; i < (n); i++)
#define len(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
using namespace std;
template<typename T> using vc = vector<T>;
template<typename T> using vv = vc<vc<T>>;
template<typename T> using vvv = vv<vc<T>>;
using vi = vc<int>;using vvi = vv<int>; using vvvi = vv<vi>;
using ll = long long;using vl = vc<ll>;using vvl = vv<ll>; using vvvl = vv<vl>;
using ld = long double; using vld = vc<ld>; using vvld = vc<vld>; using vvvld = vc<vvld>;
using uint = unsigned int;
using ull = unsigned long long;
const ld pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
// const ll mod = 1000000007;
const ll mod = 998244353;
inline bool inside(ll y, ll x, ll H, ll W) {return 0 <= (y) and (y) < (H) and 0 <= (x) and (x) < (W); }

#define debug(var)  do{std::cout << #var << " : \n";view(var);}while(0)
template<typename T> void view(T e){cout << e << endl;}
template<typename T> void view(const vc<T>& v){for(const auto& e : v){ cout << " " << e; } cout << endl;}
template<typename T> void view(const vv<T>& vv){ for(const auto& v : vv){ view(v); } }

int main(){
    int N, M; cin >> N >> M;
    vc<pair<int, int>> query;
    rep(i, N){
        int l, r; cin >> l >> r; r++;
        query.push_back({l, 1});
        query.push_back({r, -1});
    }
    query.push_back({M, -1});
    sort(all(query));
    int nw = 0, maxi = 0, l = 0, r = M;
    for (auto [x, p] : query){
        if (nw == maxi) r = x - 1;
        nw += p;
        if (nw > maxi){
            maxi = nw;
            l = x;
        }
    }
    if (maxi % 2) cout << (ll)maxi * M - M + r << endl;
    else cout << (ll)maxi * M - l << endl; 
}
accuracy: 1
time_ms: 110
memory_kb: 9316
final_rank: 3

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int main() {
    int N;
    ll M;
    cin >> N >> M;
    vector<ll> L(N), R(N);
    vector<ll> X;
    rep(i,0,N) {
        cin >> L[i] >> R[i];
        X.push_back(L[i]);
        X.push_back(R[i]);
    }
    UNIQUE(X);
    rep(i,0,N) L[i] = LB(X,L[i]), R[i] = LB(X,R[i]);
    int Len = X.size();
    vector<ll> Imos(Len+1,0);
    rep(i,0,N) {
        Imos[L[i]]++, Imos[R[i]+1]--;
    }
    rep(i,0,Len) Imos[i+1] += Imos[i];
    ll MAX = 0;
    rep(i,0,Len) chmax(MAX,Imos[i]);
    vector<ll> MAXS;
    rep(i,0,Len) {
        if (Imos[i] == MAX) MAXS.push_back(X[i]);
    }
    if (MAX % 2 == 0) {
        cout << M * MAX - MAXS[0] << endl;
    }
    else {
        cout << M * (MAX - 1) + MAXS.back() << endl;
    }
}
accuracy: 1
time_ms: 150
memory_kb: 13216
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;

int main() {
  ll N, M; cin >> N >> M;
  vector<array<ll, 2>> intervals(N);
  for (int i = 0; i < N; ++i) {
    ll l, r; cin >> l >> r;
    intervals[i] = {l, r};
  }
  
  map<ll, ll> imos;
  for (int i = 0; i < N; ++i) {
    auto [l, r] = intervals[i];
    imos[l] += 1;
    imos[r] += 0;
    imos[r+1] -= 1;
  }
  
  map<ll, ll> accum;
  ll sum = 0;
  ll res = 0;
  for (auto [key, value] : imos) {
    sum += value;
    ll tmp = 0;
    if (sum % 2 == 0) tmp = sum * M - key;
    else tmp = (sum - 1) * M + key;
    if (res < tmp) res = tmp;
  }
  cout << res << endl;
  
  return 0;
}
accuracy: 1
time_ms: 260
memory_kb: 43908
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;

void erase(multiset<array<ll, 2>> &mst, array<ll, 2> elem) {
  auto itr = mst.find(elem);
  if (itr != mst.end()) mst.erase(itr);
  return;
}

int main() {
  ll N, M; cin >> N >> M;
  vector<array<ll, 2>> intervals(N);
  multiset<array<ll, 2>> mst1, mst2;
  for (int i = 0; i < N; ++i) {
    ll l, r; cin >> l >> r;
    intervals[i] = {l, r};
    
    mst1.insert({l, r});
    mst2.insert({M-r, M-l});
  }
  
  vector<ll> ed1, ed2;
  while (mst1.size()) {
    auto [l, r] = *mst1.begin();
    erase(mst1, {l, r});
    erase(mst2, {M-r, M-l});
    
    while (1) {
      array<ll, 2> nxt = {r+1, 0};
      auto itr = mst1.lower_bound(nxt);
      if (itr != mst1.end()) {
        l = (*itr)[0], r = (*itr)[1];
        erase(mst1, {l, r});
        erase(mst2, {M-r, M-l});
      }
      else {
        break;
      }
    }
    
    ed1.emplace_back(r);
    
    swap(mst1, mst2);
    swap(ed1, ed2);
  }
  
  // for (auto n : ed1) cout << n << " ";
  // cout << endl;
  // for (auto n : ed2) cout << n << " ";
  // cout << endl;
  
  ll loop = (int)ed1.size() + (int)ed2.size() - 1;
  ll mn = *min_element(ed2.begin(), ed2.end());
  ll res = loop * M + mn;
  
  cout << res << endl;
  
  
  return 0;
}
accuracy: 0.058823529411764705
time_ms: 120
memory_kb: 19840
final_rank: 19

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

int main() {
    int N = in(), M = in();
    vector<pair<int,int>> A(N);
    for(auto &[L, R] : A) L = in(), R = in();

    vector<int> V = {0, M};
    for(auto [L, R] : A) {
        V.push_back(L);
        V.push_back(R);
    }
    unique(V);
    auto ID = [&](int x) { return lower_bound(V, x); };
    const int nV = V.size();
    vector<int> sum(nV, 0);
    for(auto [L, R] : A) {
        L = ID(L), R = ID(R) + 1;
        sum[L]++, sum[R]--;
    }
    for(int i : rep(nV - 1)) sum[i + 1] += sum[i];

    int Max = 0;
    for(int i : rep(nV)) chmax(Max, sum[i]);
    int argMaxL = [&] { for(int i :    rep(nV)) if(sum[i] == Max) return i; assert(0); }();
    int argMaxR = [&] { for(int i : revrep(nV)) if(sum[i] == Max) return i; assert(0); }();
    if(Max % 2 == 0) {
        print(i64(Max - 1) * M + M - V[argMaxL]);
    } else {
        print(i64(Max - 1) * M + V[argMaxR]);
    }
}
accuracy: 1
time_ms: 80
memory_kb: 7816
final_rank: 2

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

int main() {
    int N = in(), M = in();
    vector<pair<int,int>> A(N);
    for(auto &[L, R] : A) L = in(), R = in();

    multiset<pair<int,int>> F, B;
    for(auto [L, R] : A) {
        F.insert({L, -R});
        B.insert({-R, L});
    }

    const int INF = 2e9;
    i64 T = 0;
    while(not F.empty()) {
        i64 t = T % (2 * M);
        if(0 <= t and t < M) {
            auto itr = F.upper_bound({+t, +INF});
            if(itr == F.end()) {
                T = (T - t) + M;
            } else {
                auto [L, R] = *itr;
                R = -R;
                F.erase(F.find({L, -R}));
                B.erase(B.find({-R, L}));
                T = (T - t) + R;
            }
        } else {
            auto itr = B.upper_bound({-(2 * M - t), +INF});
            if(itr == B.end()) {
                T = (T - t) + 2 * M;
            } else {
                auto [R, L] = *itr;
                R = -R;
                F.erase(F.find({L, -R}));
                B.erase(B.find({-R, L}));
                T = (T - t) + 2 * M - L;
            }
        }
    }
    print(T);
}
accuracy: 0.058823529411764705
time_ms: 100
memory_kb: 14532
final_rank: 17

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll=long long;
using vll=vector<ll>;
using vvll=vector<vll>;
#define rep(i,n) for(ll i=0;i<ll(n);i++)



int main(){
    ll N,M;
    cin>>N>>M;
    vll L(N),R(N);
    map<ll,ll> MP;
    rep(i,N){
        cin>>L[i]>>R[i];
        MP[L[i]]=MP[R[i]]=1;
    }
    vll D;
    for(auto m:MP){
        MP[m.first]=D.size();
        D.push_back(m.first);
    }
    ll DN=D.size();
    vll V(DN+1,0);
    rep(i,N){
        L[i]=MP[L[i]];
        R[i]=MP[R[i]];
        V[L[i]]++;
        V[R[i]+1]--;
    }
    ll MX=V[0];
    vll MXV={0};
    rep(i,DN){
        V[i+1]+=V[i];
        if(MX==V[i+1]){
            MXV.push_back(i+1);
        }
        else if(MX<V[i+1]){
            MX=V[i+1];
            MXV={i+1};
        }
    }
    if(MX%2==1){
        cout<<M*(MX-1)+D[MXV.back()]<<endl;
    }
    else{
        cout<<M*(MX-1)+M-D[MXV[0]]<<endl;
    }
}
accuracy: 1
time_ms: 380
memory_kb: 38076
final_rank: 8

code_snippet: #include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#ifdef RUTHEN_LOCAL
#include <debug.hpp>
#else
#define show(x) true
#endif

using namespace std;

#define REP(i, n) for (int i = 0; i < (n); i++)

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    long long N, M;
    cin >> N >> M;
    vector<pair<long long, long long>> LR(N), LRrev(N);
    REP(i, N) {
        int l, r;
        cin >> l >> r;
        LR[i] = {l, r + 1};
        LRrev[i] = {M - r, M - l + 1};
    }
    auto cmp = [&](pair<long long, long long> a, pair<long long, long long> b) -> bool {
        if (a.second != b.second) return a.second < b.second;
        return a.first < b.first;
    };
    sort(LR.begin(), LR.end(), cmp);
    sort(LRrev.begin(), LRrev.end(), cmp);
    long long res;
    {
        multiset<long long> st;
        st.insert(0);
        REP(i, N) {
            auto [l, r] = LR[i];
            auto it = st.upper_bound(l);
            if (it == st.begin()) {
                st.insert(r);
            } else {
                it--;
                st.erase(it);
                st.insert(r);
            }
        }
        if (st.size() % 2 == 1) {
            res = M * (st.size() - 1) + *st.begin() - 1;
        }
    }
    {
        multiset<long long> st;
        st.insert(0);
        REP(i, N) {
            auto [l, r] = LRrev[i];
            auto it = st.upper_bound(l);
            if (it == st.begin()) {
                st.insert(r);
            } else {
                it--;
                st.erase(it);
                st.insert(r);
            }
        }
        if (st.size() % 2 == 0) {
            res = M * (st.size() - 1) + *st.begin() - 1;
        }
    }
    cout << res << '\n';
    return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 18672
final_rank: 4

code_snippet: #include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#ifdef RUTHEN_LOCAL
#include <debug.hpp>
#else
#define show(x) true
#endif

using namespace std;

#define REP(i, n) for (int i = 0; i < (n); i++)

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    long long N, M;
    cin >> N >> M;
    vector<pair<long long, long long>> LR(N), LRrev(N);
    REP(i, N) {
        int l, r;
        cin >> l >> r;
        LR[i] = {l, r + 1};
        LRrev[i] = {M - r, M - l + 1};
    }
    auto cmp = [&](pair<long long, long long> a, pair<long long, long long> b) -> bool {
        if (a.second != b.second) return a.second < b.second;
        return a.first < b.first;
    };
    sort(LR.begin(), LR.end(), cmp);
    sort(LRrev.begin(), LRrev.end(), cmp);
    long long res = 1LL << 60;
    {
        priority_queue<long long, vector<long long>, greater<long long>> que;
        que.push(0);
        int ans = 1;
        REP(i, N) {
            auto [l, r] = LR[i];
            if (que.top() <= l) {
                que.pop();
                que.push(r);
            } else {
                ans++;
                que.push(r);
            }
        }
        if (ans % 2 == 1) {
            res = M * (ans - 1) + que.top() - 1;
        }
    }
    {
        priority_queue<long long, vector<long long>, greater<long long>> que;
        que.push(0);
        int ans = 1;
        REP(i, N) {
            auto [l, r] = LRrev[i];
            if (que.top() <= l) {
                que.pop();
                que.push(r);
            } else {
                ans++;
                que.push(r);
            }
        }
        if (ans % 2 == 0) {
            if (ans == 0) {
                res = que.top() - 1;
            } else {
                res = M * (ans - 1) + que.top() - 1;
            }
        }
    }
    cout << res << '\n';
    return 0;
}
accuracy: 0.058823529411764705
time_ms: 30
memory_kb: 8112
final_rank: 14

code_snippet: #include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#ifdef RUTHEN_LOCAL
#include <debug.hpp>
#else
#define show(x) true
#endif

using namespace std;

#define REP(i, n) for (int i = 0; i < (n); i++)

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    long long N, M;
    cin >> N >> M;
    vector<pair<long long, long long>> LR(N), LRrev(N);
    REP(i, N) {
        int l, r;
        cin >> l >> r;
        LR[i] = {l, r + 1};
        LRrev[i] = {M - r, M - l + 1};
    }
    sort(LR.begin(), LR.end());
    sort(LRrev.begin(), LRrev.end());
    long long res = 1LL << 60;
    {
        priority_queue<long long, vector<long long>, greater<long long>> que;
        que.push(0);
        int ans = 1;
        REP(i, N) {
            auto [l, r] = LR[i];
            if (que.top() <= l) {
                que.pop();
                que.push(r);
            } else {
                ans++;
                que.push(r);
            }
        }
        if (ans % 2 == 1) {
            res = M * (ans - 1) + que.top() - 1;
        }
    }
    {
        priority_queue<long long, vector<long long>, greater<long long>> que;
        que.push(0);
        int ans = 1;
        REP(i, N) {
            auto [l, r] = LRrev[i];
            if (que.top() <= l) {
                que.pop();
                que.push(r);
            } else {
                ans++;
                que.push(r);
            }
        }
        if (ans % 2 == 0) {
            if (ans == 0) {
                res = que.top() - 1;
            } else {
                res = M * (ans - 1) + que.top() - 1;
            }
        }
    }
    cout << res << '\n';
    return 0;
}
accuracy: 0.058823529411764705
time_ms: 30
memory_kb: 7532
final_rank: 12

code_snippet: #include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#ifdef RUTHEN_LOCAL
#include <debug.hpp>
#else
#define show(x) true
#endif

using namespace std;

#define REP(i, n) for (int i = 0; i < (n); i++)

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    long long N, M;
    cin >> N >> M;
    vector<pair<long long, long long>> LR(N), LRrev(N);
    REP(i, N) {
        int l, r;
        cin >> l >> r;
        LR[i] = {l, r + 1};
        LRrev[i] = {M - r, M - l + 1};
    }
    sort(LR.begin(), LR.end());
    sort(LRrev.begin(), LRrev.end());
    long long res = 1LL << 60;
    {
        priority_queue<long long, vector<long long>, greater<long long>> que;
        que.push(0);
        int ans = 1;
        REP(i, N) {
            auto [l, r] = LR[i];
            if (que.top() <= l) {
                que.pop();
                que.push(r);
            } else {
                ans++;
                que.push(r);
            }
        }
        if (ans % 2 == 1) {
            res = M * (ans - 1) + que.top() - 1;
        }
    }
    {
        priority_queue<long long, vector<long long>, greater<long long>> que;
        que.push(0);
        int ans = 1;
        REP(i, N) {
            auto [l, r] = LRrev[i];
            if (que.top() <= l) {
                que.pop();
                que.push(r);
            } else {
                ans++;
                que.push(r);
            }
        }
        if (ans % 2 == 0) {
            if (ans == 0) {
                res = que.top();
            } else {
                res = M * (ans - 1) + que.top() - 1;
            }
        }
    }
    cout << res << '\n';
    return 0;
}
accuracy: 0.058823529411764705
time_ms: 30
memory_kb: 7636
final_rank: 13