2021杭电多校1 G Pass!

题目描述

https://acm.hdu.edu.cn/showproblem.php?pid=6956

Solution

首先能够得到递推式 $f_k=(n-2)f_{k-1}+(n-1)f_{k-2}$

带入 $f_0,f_1$ 可以得到通项公式为 $f_k=(n-1)^k+(n-1)(-1)^k$

那么我们需要求最小的 $t$ 使得 $\frac 1 n [(n-1)^t+(n-1)(-1)^t]\equiv x(\bmod p)$

我们考虑奇偶分类把 $(-1)^t$ 去掉,然后直接 $bsgs$ 即可

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
#include <iostream>
#include <cmath>
#include <unordered_map>
#define ll long long
using namespace std;

const int p = 998244353;

ll pow_mod(ll x, ll n) {
ll s = 1;
for (; n; n >>= 1, x = x * x % p)
if (n & 1) s = s * x % p;
return s;
}

ll n, x;

unordered_map<int, int> mp1, mp2;
int bsgs(int p, int a, int b1, int b2) {
int q = ceil(sqrt(p)); ll mul = 1; mp1.clear(); mp2.clear();
for (int i = 0; i <= q; ++i) {
mp1[mul * b1 % p] = i;
mp2[mul * b2 % p] = i;
mul = mul * a % p;
}
mul = 1; ll aq = pow_mod(a, q);
for (int i = 1; i <= q; ++i) {
mul = mul * aq % p;
if (mp1.find(mul) != mp1.end()) return (i * q - mp1[mul]) * 2;
if (mp2.find(mul) != mp2.end()) return (i * q - mp2[mul]) * 2 + 1;
} return -1;
}

void work() {
cin >> n >> x;
if (x == 1) return cout << 0 << "\n", void();
if (x == 0) return cout << 1 << "\n", void();
x = x * n % p;
int ans = bsgs(p, (n - 1) * (n - 1) % p, (x - n + 1 + p) % p, (x + n - 1) * pow_mod(n - 1, p - 2) % p), Ans = p + 1;
if (~ans) cout << ans << "\n";
else cout << -1 << "\n";
}

int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

int T; cin >> T;
while (T--) work();
return 0;
}