#include using LL = long long; const int N = 2e5 + 7; LL ans; int n, m, k, cnt, ok; std::vector> a[N * 2]; std::vector b[N * 2]; std::map mp; void solve(const std::vector> &a) { int now = N, lo = N, hi = N; for(auto &&[x, y]: a) if(y) { b[++now].push_back(x); hi = std::max(hi, now); } else { b[now--].push_back(x); lo = std::min(lo, now); } if(now < N) ok = 0; for(int i = lo; i <= hi; ++i) { if(~b[i].size() & 1) for(int j = 1; j < b[i].size(); j += 2) ans += b[i][j] - b[i][j - 1]; else { std::vector t(b[i].size()); for(int j = int(b[i].size()) - 3; j >= 0; j -= 2) t[j] = t[j + 2] + b[i][j + 2] - b[i][j + 1]; LL sum = 0, val = t[0]; for(int j = 2; j < b[i].size(); j += 2) { sum += b[i][j - 1] - b[i][j - 2]; val = std::min(val, sum + t[j]); } ans += val; } b[i].resize(0); } } int main() { scanf("%d%d%d", &n, &m, &k); for(int i = 1, x; i <= n; ++i) { scanf("%d", &x); if(!mp.count(x % k)) mp[x % k] = ++cnt; a[mp[x % k]].push_back({x / k, n >= m}); } for(int i = 1, x; i <= m; ++i) { scanf("%d", &x); if(!mp.count(x % k)) mp[x % k] = ++cnt; a[mp[x % k]].push_back({x / k, n < m}); } ok = 1; for(auto &&[_, c]: mp) { std::sort(a[c].begin(), a[c].end()); solve(a[c]); } printf("%lld\n", ok ? ans : -1LL); return 0; }