Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P4774 [NOI2018] 屠龙勇士

P4774 [NOI2018] 屠龙勇士

注意到攻击的顺序是确定的,每次选择的剑的集合是确定的,那么可以确定出每次攻击使用的剑。考虑杀死龙的条件,一定有 $x \times ATK _ i \ge a _ i, x \times ATK _ i \equiv a _ i \mod p _ i$ 。根据前式,可以解出 $x$ 的最小值,再考虑后式。考虑先将式子 $ATK _ i, a _ i , p _ i$ 除以它们的最小公倍数,两侧再同时乘 $ATK _ i ^ {-1} \mod p _ i$ ,如果 $ATK _ i$ 在 $\bmod p _ i$ 意义下没有逆元,即 $\gcd(ATK _ i, p _ i) > 1$ ,那么一定无解。最后可以将式子化为 $n$ 个 $x \equiv w _ i \mod v _ i$ 的形式,可以用 ExCRT 解得答案。

查看代码
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;
}