#include #include using namespace std; int main() { int N, L; cin >> N >> L; set s, t; for (int i = 0; i < N; ++i) { int x; cin >> x; s.insert(x); } for (int i = 0; i < N; ++i) { int y; cin >> y; t.insert(y); } long long pos = 0; for (int i = 0; i < N; ++i) { set::iterator it = s.lower_bound(pos % L); if (it != s.end()) pos += *it - pos % L, s.erase(it); else pos += *s.begin() % L - pos % L + L, s.erase(s.begin()); if (i + 1 == N) { pos += (*t.begin() - pos % L + L) % L; } else { long long nxt = pos; it = t.lower_bound(nxt % L); if (it != t.end()) nxt += *it - nxt % L; else nxt += *t.begin() - nxt % L + L; it = s.lower_bound(nxt % L); if (it != s.end()) nxt += *it - nxt % L; else nxt += *s.begin() - nxt % L + L; it = t.lower_bound(nxt % L); if (it != t.begin()) --it, pos = nxt - (nxt % L - *it), t.erase(it); else it = --t.end(), pos = nxt - (nxt % L - *it + L), t.erase(it); } } cout << pos << endl; return 0; }