题意:给你一个递推式,然后你会得到一场长度为n的序列,然后给你一个数,让你找出序列中最小下标的数等于这个数。
思路:bsgs算法的基本应用
我们可以发现该数列的递推式可以化简成如下的形式
我们就可把右边当成一个整体,因为p的大小为1e9+9,所以我们可以选择将n分解成x1*1001-x2,x1<=1000000;
这样我们就可以预处理x1*1001的值,然后在每次询问时枚举余数查询即可;
注意当a=0和a=1特例的情况.
附上代码:
#include <cstring>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <map>
#include <unordered_map>
#include <algorithm>
using namespace std;
typedef long long ll;
long long mod;
ll pow_mod(ll a, ll b) {
ll ans = 1;
while (b > 0) {
if (b & 1) ans = ans * a % mod;
a = a * a % mod;
b /= 2;
}
return ans;
}
long long x1 = 1000000;
long long x2 = 1001;
#define N 10000007
class mapp {
public:
int hs[N], head[N], nxt[N], id[N], top;
inline void insert(int x, int y)
{
int k = x % N;
hs[top] = x, id[top] = y, nxt[top] = head[k], head[k] = top++;
}
inline int find(int x)
{
int k = x % N;
for (int i = head[k]; i != -1; i = nxt[i]) if (hs[i] == x) return id[i];
return -1;
}
inline void init() {
top = 0;
memset(head, -1, sizeof(head));
}
}mp;
int main(void) {
int t;
scanf("%d", &t);
while (t--) {
mp.init();
ll n, x0, a, b, p;
scanf("%lld%lld%lld%lld%lld", &n, &x0, &a, &b, &p);
mod = p;
long long x = pow_mod(a, x2);
long long y = 1;
for (int i = 1; i <= x1; i++) {
y = y * x%mod;
if (mp.find(y) == -1) {
mp.insert(y, i);
}
}
int q;
scanf("%d", &q);
long long v;
if (a == 0) {
while (q--) {
scanf("%lld", &v);
if (v == x0) printf("0\n");
else if (v == b) printf("1\n");
else printf("-1\n");
}
}
else if (a == 1) {
while (q--) {
scanf("%lld", &v);
long long ans = ((v - x0) % mod + mod) % mod*pow_mod(b, mod - 2) % mod;
if (ans < n) {
printf("%lld\n", ans);
}
else printf("-1\n");
}
}
else {
while (q--) {
scanf("%lld", &v);
long long inv = pow_mod(((b + a % mod * (x0%mod) % mod) % mod - x0 + mod) % mod, mod - 2);
v = (v * (a - 1) % mod + b) % mod*inv%mod;
y = v;
long long maxx = mod + 1;
for (int i = 0; i <= x2; i++) {
if (mp.find(y) != -1) {
maxx = min(maxx, (long long)mp.find(y)*x2 - i);
}
y = y * (a%mod) % mod;
}
if (maxx >= n || maxx == mod + 1) {
printf("-1\n");
}
else printf("%lld\n", maxx);
}
}
}
}
/*
1
1000000000000000000 1 5 0 1000000007
6
0
1
10
1000000006
12345678
1234567
*/