#include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; using ld = long double; using pint = pair; using pll = pair; #define MOD 1000000007LL #define INF 1000000000LL #define EPS 1e-10 #define FOR(i,n,m) for(ll i=n;i<(int)m;i++) #define REP(i,n) FOR(i,0,n) #define DUMP(a) REP(d,a.size()){cout<> n >> l; set xx, yy; REP(i, n) { ll tmp; cin >> tmp; xx.insert(tmp); } REP(i, n) { ll tmp; cin >> tmp; yy.insert(tmp); } ll lb = 0, ub = INF * INF; while(ub - lb > 1) { ll m = (ub + lb) / 2; ll pos = m % l, tmp = 0; set x = xx, y = yy; REP(i, n) { auto ite = y.upper_bound(pos); if(ite == y.begin()) { tmp += pos; pos = l; ite = y.end(); ite--; } else ite--; tmp += pos - *ite; pos = *ite; y.erase(ite); ite = x.upper_bound(pos); if(ite == x.begin()) { tmp += pos; pos = l; ite = x.end(); ite--; } else ite--; tmp += pos - *ite; pos = *ite; x.erase(ite); } tmp += pos; if(tmp > m) lb = m; else ub = m; } cout << ub << endl; return 0; } /* --------------------------------------- */