import std.stdio, std.array, std.string, std.conv, std.algorithm; import std.typecons, std.range, std.random, std.math, std.container; import std.numeric, std.bigint, core.bitop, core.stdc.string; immutable long MOD = 10^^9 + 7; void main() { auto s = readln.split; auto N = s[0].to!int; auto L = s[1].to!long; auto A = readln.split.map!(to!long).array; auto B = readln.split.map!(to!long).array; Tuple!(int, int, int, long)[] C; for (int i = 0, j = 0; i < N || j < N; ) { if (j >= N || (i < N && A[i] < B[j])) { if (!C.empty && C.back[2] == 0) { C.back[1] = i; C.back[3] = A[i]; } else { C ~= tuple(i, i, 0, A[i]); } ++i; } else { if (!C.empty && C.back[2] == 1) { C.back[1] = j; C.back[3] = B[j]; } else { C ~= tuple(j, j, 1, B[j]); } ++j; } } if (C.back[2] == C.front[2]) { auto t = C.back; C.popBack; C.front[0] = t[0]; } auto rbt = new RedBlackTree!(Tuple!(int, int, int, long), "a[3] < b[3]"); rbt.insert(C); long ans = 0; long pos = 0; int turn = 0; foreach (_; 0..2*N) { auto ub = rbt.upperBound(tuple(0, 0, 0, pos)); if (ub.empty) { ub = rbt.upperBound(tuple(0, 0, 0, 0L)); } else if (ub.front == rbt.back) { if (turn != ub.front[2]) ub = rbt.upperBound(tuple(0, 0, 0, 0L)); } if (turn != ub.front[2]) { ub.popFront; if (ub.empty) ub = rbt.upperBound(tuple(0, 0, 0, 0L)); } auto tar = ub.front; long next = tar[3]; if (pos < next) ans += next - pos; else ans += L - pos + next; pos = next; rbt.removeKey(tar); if (tar[0] != tar[1]) { tar[1] -= 1; if (tar[1] < 0) tar[1] = N - 1; if (tar[2] == 0) tar[3] = A[tar[1]]; else tar[3] = B[tar[1]]; rbt.insert(tar); } turn ^= 1; } ans.writeln; }