#include #include #define llint long long using namespace std; llint n, l; set S, T; llint dist(llint s, llint t) { if(s > t) return t+l - s; else return t-s; } set::iterator succ(set &S, llint x) { auto p = S.upper_bound(x); if(p == S.end()) p = S.begin(); return p; } set::iterator pred(set &S, llint x) { auto p = S.lower_bound(x); if(p == S.begin()) p = S.end(); p--; return p; } int main(void) { cin >> n >> l; llint x; for(int i = 1; i <= n; i++) cin >> x, S.insert(x); for(int i = 1; i <= n; i++) cin >> x, T.insert(x); llint ans = 0, pos = 0; for(int i = 1; i < n; i++){ auto p = succ(S, pos); p = succ(T, *p); p = pred(S, *p); ans += dist(pos, *p); pos = *p; S.erase(p); p = succ(T, pos); p = succ(S, *p); p = pred(T, *p); ans += dist(pos, *p); pos = *p; T.erase(p); } auto p = succ(S, pos); ans += dist(pos, *p); pos = *p; S.erase(p); p = succ(T, pos); ans += dist(pos, *p); pos = *p; T.erase(p); cout << ans << endl; return 0; }