1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #include <cstdio> #include <set> using namespace std; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0'; flag && (x = ~x + 1); } template <class Type, class ...rest> void read (Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write (Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar('0' + x % 10); } typedef __int128 L; typedef long long LL; const int N = 1e5 + 10; const LL inf = 1e12 + 1; int n, m; LL w[N], atk[N], v[N], nswd[N]; multiset <LL> swd; LL gcd (LL a, LL b) { return b ? gcd(b, a % b) : a; } LL lcm (LL a, LL b) { return a / gcd(a, b) * b; } LL exgcd (LL a, LL b, LL &x, LL &y) { if (!b) return x = 1, y = 0, a; LL d = exgcd(b, a % b, y, x); y -= a / b * x; return d; } LL inv (LL a, LL p) { LL x, y; exgcd(a, p, x, y); return (x % p + p) % p; } void calc () { read(n, m); for (int i = 1; i <= n; ++i) read(w[i]); for (int i = 1; i <= n; ++i) read(v[i]); for (int i = 1; i <= n; ++i) read(nswd[i]); swd.clear(); swd.insert(0), swd.insert(inf); for (LL a; m; --m) read(a), swd.insert(a); for (int i = 1; i <= n; ++i) { auto t = --swd.upper_bound(w[i]); if (!*t) ++t; atk[i] = *t; swd.erase(t); swd.insert(nswd[i]); } LL mn = 0; for (int i = 1; i <= n; ++i) { mn = max(mn, (w[i] - 1) / atk[i] + 1); LL d = gcd(gcd(w[i], v[i]), atk[i]); w[i] /= d, v[i] /= d, atk[i] /= d; if (gcd(atk[i], v[i]) > 1) return void(puts("-1")); w[i] = (L)w[i] * inv(atk[i], v[i]) % v[i]; } LL b = w[1], p = v[1], x, y; for (int i = 2; i <= n; ++i) { LL d = gcd(v[i], p); if ((w[i] - b) % d) return void(puts("-1")); exgcd(p / d, v[i] / d, x, y); x = ((L)(w[i] - b) / d * x % v[i] + v[i]) % v[i]; L t = b + (L)p * x; p = lcm(p, v[i]); b = (t % p + p) % p; } if (b < mn) b += p * ((mn - b - 1) / p + 1); write(b), puts(""); } int main () { int T; read(T); while (T--) calc(); return 0; }
|