#include #include #include using namespace std; void solve() { const int inf = 1e9; int n, m; cin >> n >> m; vector a(m), b(m); for (int i = 0; i < m; ++i) cin >> a[i]; for (int i = 0; i < m; ++i) cin >> b[i]; vector> ab(m); for (int i = 0; i < m; ++i) ab[i] = {a[i], b[i]}; sort(ab.begin(), ab.end()); for (int i = 1; i < m; ++i) { if (ab[i - 1].second > ab[i].second || (ab[i].first != ab[i - 1].first && ab[i].second == ab[i - 1].second) || (ab[i - 1] == ab[i] && ab[i - 1].first != ab[i - 1].second)) { cout << -1 << endl; return; } } auto cal = [](long long l, long long s, long long g, long long r) -> int { if (s == g) return 0; int ret = 0; while (s < g) { ++ret; long long ns = min((s + r) / 2, g); s = ns; } while (s > g) { ++ret; long long ns = max((s + l + 1) / 2, g); s = ns; } return ret; }; auto cal2 = [](long long s1, long long g1, long long g2, long long s2) -> int { long long d1 = g2 - g1, d2 = s2 - s1; int ret = 1; long long tmp = d2; while ((tmp + 1) / 2 > d1) { ++ret; tmp = (tmp + 1) / 2; } if (min(g1 - s1, s2 - g2) < tmp - d1) ++ret; return max(2, ret); }; int ans = 0; if (ab[0].first > ab[0].second) ++ans; if (ab[m - 1].first < ab[m - 1].second) ++ans; for (int i = 0; i + 1 < m; ++i) { if (ab[i].first < ab[i].second) { if (ab[i + 1].first > ab[i + 1].second) ans += cal2(ab[i].first, ab[i].second, ab[i + 1].second, ab[i + 1].first); else ans += cal(-inf, ab[i].first, ab[i].second, ab[i + 1].second); } else if (ab[i + 1].first > ab[i + 1].second) ans += cal(ab[i].second, ab[i + 1].first, ab[i + 1].second, inf + inf); } cout << ans << endl; } int main() { int t; cin >> t; while (t--) solve(); }