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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| #include<bits/stdc++.h> #define int long long using namespace std; template <class T> inline void read(T &res) { res = 0; bool flag = 0; char c = getchar(); while('0' > c || c > '9') { if(c == '-') flag = 1; c = getchar();} while('0' <= c && c <= '9') res = (res << 3) + (res << 1) + (c ^ 48), c = getchar(); if(flag) res = -res; } template <class T, class ...Arg> inline void read(T &res, Arg &...com){ read(res), read(com...);} template <class T> void out(T res) { if(res > 9) out(res / 10); putchar(res % 10 + '0'); } template <class T> inline void write(T res) { if(res < 0) putchar('-'), res = -res; out(res), putchar('\n'); } const int N = 1e5 + 5; int n, m, T; int a[N], p[N], gn[N], sword[N]; multiset<int> s; int gcd(int x, int y) { return y ? gcd(y, x % y) : x; } inline int qpow(int x, int k, int mod) { int res = 1; while(k) { if(k & 1) res = (__int128)res * x % mod; x = (__int128)x * x % mod; k >>= 1; } return res; } void exgcd(int a, int b, __int128 &x, __int128 &y) { if(!b) return x = 1, y = 0, void(); exgcd(b, a % b, y, x); y -= a / b * x; } inline int Lcm(int x, int y) { return (__int128) x * y / gcd(x, y); } inline bool merge(int j) { __int128 x, y; if((a[j] - a[1]) % gcd(p[1], -p[j]) != 0) return 0; exgcd(p[1], p[j], x, y); int mod = Lcm(p[1], p[j]); x = (__int128) x * (a[j] - a[1]) / gcd(p[1], p[j]); a[1] = ((__int128) p[1] * x + a[1] + mod) % mod; p[1] = mod; return 1; } int minn, ans;
inline int Inv(int a, int p) { if (gcd(a, p) != 1) return -1; __int128 x, y; exgcd(a, p, x, y); return (x % p + p) % p; }
inline void work() { s.clear(); minn = 0; read(n, m); for(int i = 1;i <= n;i ++) read(a[i]); for(int i = 1;i <= n;i ++) read(p[i]); for(int i = 1;i <= n;i ++) read(gn[i]); for(int i = 1, o;i <= m;i ++) read(o), s.insert(o); for(int i = 1;i <= n;i ++) { auto t = s.upper_bound(a[i]); if (t != s.begin()) -- t; sword[i] = *t; s.erase(t); s.insert(gn[i]); } for(int i = 1, o;i <= n;i ++) { minn = max(minn, (int)ceil((double)a[i] / sword[i])); if(gcd(sword[i], p[i]) != 1) { o = gcd(sword[i], p[i]); if(a[i] % o != 0) return puts("-1"), void(); a[i] /= o, p[i] /= o, sword[i] /= o; } a[i] = (__int128)a[i] * Inv(sword[i], p[i]) % p[i]; } for(int i = 2;i <= n;i ++) if(!merge(i)) return puts("-1"), void(); ans = (a[1] + p[1]) % p[1]; if (minn > a[1]) ans = ans + ((minn - a[1] + p[1] - 1) / p[1]) * p[1]; write(ans); } signed main() { read(T); while(T --) work(); return 0; }
|