#include using namespace std; const long long INF = 1000000000000000000; int main(){ int N, M, K; cin >> N >> M >> K; vector B(N); for (int i = 0; i < N; i++){ cin >> B[i]; } vector R(M); for (int i = 0; i < M; i++){ cin >> R[i]; } map, vector>> mp; for (int i = 0; i < N; i++){ mp[B[i] % K].first.push_back(i); } for (int i = 0; i < M; i++){ mp[R[i] % K].second.push_back(i); } int edge = 0; long long ans = 0; for (auto &P : mp){ int r = P.first; vector id1 = P.second.first; vector id2 = P.second.second; int cnt1 = id1.size(); int cnt2 = id2.size(); edge += min(cnt1, cnt2); vector B2, R2; for (int i = 0; i < cnt1; i++){ B2.push_back((B[id1[i]] - r) / K); } for (int i = 0; i < cnt2; i++){ R2.push_back((R[id2[i]] - r) / K); } sort(B2.begin(), B2.end()); sort(R2.begin(), R2.end()); if (cnt1 > cnt2){ swap(cnt1, cnt2); swap(B2, R2); } assert((long long) cnt1 * cnt2 <= 100000000); vector> dp(cnt1 + 1, vector(cnt2 + 1, INF)); dp[0][0] = 0; for (int i = 0; i <= cnt1; i++){ for (int j = 0; j <= cnt2; j++){ if (j > 0){ dp[i][j] = min(dp[i][j], dp[i][j - 1]); if (i > 0){ dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + abs(B2[i - 1] - R2[j - 1])); } } } } ans += dp[cnt1][cnt2]; } if (edge != min(N, M)){ cout << -1 << endl; } else { cout << ans << endl; } }