#include #include using namespace atcoder; using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf 1000000000000000000 array op(array a,array b){ rep(i,2)a[i] = max(a[i],b[i]); return a; } array e(){ return array{-1,-1}; } int main(){ int N; cin>>N; long long L; cin>>L; vector> V(2*N); rep(i,N){ scanf("%lld",&V[i].first); V[i].second = 0; } rep(i,N){ scanf("%lld",&V[i+N].first); V[i+N].second = 1; } sort(V.begin(),V.end()); vector> y(4*N,e()); rep(i,2*N){ y[i][V[i].second] = i; y[i+2*N][V[i].second] = 2*N+i; } segtree,op,e> seg(y); vector ans; int now = 0; while(ans.size()!=2*N){ int temp = 0; if(ans.size()>0)temp = ans.back(); int ok = 4*N,ng = temp; while(ok-ng>1){ int mid = (ok+ng)/2; array ret = seg.prod(temp,mid); if(ret[now]==-1)ng = mid; else ok = mid; } int x; { array ret = seg.prod(temp,ok); x = ret[now^1]; } ok = temp,ng = 4*N; while(ng-ok>1){ int mid = (ok+ng)/2; array ret = seg.prod(temp,mid); if(ret[now^1]<=x)ok = mid; else ng = mid; } array ret = seg.prod(temp,ok); x = ret[now]%(2*N); ans.push_back(x); seg.set(x,e()); seg.set(x+2*N,e()); now ^= 1; } long long Ans = 0LL; rep(i,2*N){ if(i==0)Ans += V[ans[i]].first; else{ long long temp = V[ans[i]].first - V[ans[i-1]].first; if(temp<0)temp += L; Ans += temp; } } cout<