#include #include using namespace atcoder; using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf 1000000000000000000 vector op(vector a,vector b){ rep(i,2)a[i] = max(a[i],b[i]); return a; } vector e(){ return vector(2,-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()); segtree,op,e> seg(4*N); rep(i,2*N){ vector temp(2,-1); temp[V[i].second] = i; seg.set(i,temp); temp[V[i].second] = 2*N+i; seg.set(2*N+i,temp); } 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; vector ret = seg.prod(temp,mid); if(ret[now]==-1)ng = mid; else ok = mid; } int x; { vector ret = seg.prod(temp,ok); x = ret[now^1]; } ok = temp,ng = 4*N; while(ng-ok>1){ int mid = (ok+ng)/2; vector ret = seg.prod(temp,mid); if(ret[now^1]<=x)ok = mid; else ng = mid; } vector ret = seg.prod(temp,ok); x = ret[now]%(2*N); ans.push_back(x); seg.set(x,vector(2,-1)); seg.set(x+2*N,vector(2,-1)); 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<