#include #include #include #include using namespace std; long long N, K, P; long long A[1 << 18], B[1 << 18]; long long SB[20000009]; bool solve(long long border) { long long sum = 0; for (int i = 1; i <= N; i++) { long long cl = P - A[i] - 1LL; long long cr = P - A[i] + border; sum += SB[cr] - SB[cl]; } if (sum >= K) return true; return false; } int main() { // Step #1. Input cin >> N >> K >> P; for (int i = 1; i <= N; i++) cin >> A[i]; for (int i = 1; i <= N; i++) cin >> B[i]; assert(1 <= N && N <= 100000); assert(1 <= K && K <= N * N); assert(2 <= P && P <= 10000000); for (int i = 1; i <= N; i++) assert(0 <= A[i] && A[i] < P); for (int i = 1; i <= N; i++) assert(0 <= B[i] && B[i] < P); // Step #2. Prepare for (int i = 1; i <= N; i++) SB[B[i]] += 1; for (int i = 1; i <= N; i++) SB[B[i] + P] += 1; for (int i = 1; i <= 2 * P; i++) SB[i] += SB[i - 1]; // Step #3. Binary Search long long cl = 0, cr = P, cm, minx = (1LL << 60); for (int i = 0; i < 30; i++) { cm = (cl + cr) / 2LL; bool I = solve(cm); if (I == true) { minx = min(minx, cm); cr = cm; } else { cl = cm; } } // Step #4. Output cout << minx << endl; return 0; }