怎么这也是个可搞题啊,被F耽误了两个可搞题
我们发现第 n 项是这样的:b + ba + ba^2 + ba^3 + ... + ba^(n - 1) + x0a^n
我们等比数列求和简化一下:
我们要解这个n,就把n当做未知数解一下:
ok,这样就可以用BSGS解这个方程了,不会BSGS? 那就继续往下看:
为了方便,我们把右边这一坨看成V好了。在同余的情况下,n最大不超过mod,我们把n分解为 x*t1 - t2
令t1 = 1000,t2 <= 1000,那么x最大1e6:
我们预处理存下所有的,每次询问,我们枚举 t2 只用 1000 log 的复杂度就可以解出这个方程(有点卡常,3900ms过的)
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int mod, t1 = 1001,t2 = 1e6;
ll ksm(ll x, int y) {
ll res = 1;
while (y) {
if (y & 1)
res = res * x % mod;
x = x * x % mod;
y /= 2;
}
return res;
}
unordered_map<int, int> mp;
int main() {
int T, x0, a, b, q;
scanf("%d", &T);
while (T--) {
mp.clear();
ll n;
scanf("%lld%d%d%d%d%d", &n, &x0, &a, &b, &mod, &q);
ll s = ksm(a, t1);
int x = 1;
for (int i = 1; i <= t2; i++) {
x = 1ll * x * s % mod;
if (!mp.count(x))
mp[x] = i * t1;
}
ll mu = (b + 1ll * a * x0 % mod - x0 + mod) % mod;
int inv = ksm(mu, mod - 2);
while (q--) {
ll v;
cin>>v;
if (!a) {
if (v == x0)
puts("0");
else if (v == b)
puts("1");
else
puts("-1");
continue;
}
if (a == 1) {
ll ans = (v - x0 + mod) * ksm(b, mod - 2) % mod;
if (ans < n)
printf("%lld\n", ans);
else
puts("-1");
continue;
}
int ans = mod + 1;
v = (v * (a - 1) % mod + b) * inv % mod;
int y = v;
for (int i = 0; i <= t1; i++) {
if (mp.count(y))
ans = min(ans, mp[y] - i);
y =1ll * y * a % mod;
}
if (ans == mod + 1 || 1ll * ans >= n)
puts("-1");
else
printf("%d\n", ans);
}
}
}