#include #include #include #include #include using namespace std; int main() { int N; long long L; cin >> N >> L; vector A(N), B(N); for (int i = 0; i < N; i++) cin >> A[i]; for (int i = 0; i < N; i++) cin >> B[i]; set a, b; for (int i = 0; i < N; i++) { a.insert(A[i]); a.insert(A[i] + L); b.insert(B[i]); b.insert(B[i] + L); } long long ans = 0; long long x = 0; for (int i = 0; i < N; i++) { { auto it = a.lower_bound(x); ans += *it - x; x = *it % L; auto it2 = b.lower_bound(x); auto it3 = prev(a.lower_bound(*it2)); ans += *it3 - x; x = *it3 % L; a.erase(x); a.erase(x + L); } { if (!a.empty()) { auto it = b.lower_bound(x); ans += *it - x; x = *it % L; auto it2 = a.lower_bound(x); auto it3 = prev(b.lower_bound(*it2)); ans += *it3 - x; x = *it3 % L; b.erase(x); b.erase(x + L); } else { ans += *b.lower_bound(x) - x; } } } cout << ans << '\n'; }