紫书例题:
已知 递推公式 Xi = (a * Xi-1 + b ) % 10001; 给定奇数项,找合适的 a b 满足递推公式,补全整个数列;
可以 枚举 a b ,,但效率堪忧 ,然后可以枚举 a,来计算出 b,(对10001取模,所以 a < 10001, 效率可以)
X2 = ( a * X1 + b ) % 10001;
X3 = (a * X2 + b ) % 10001;
以上两式联立得出 : 10001 * k - (a+1)*b = a * a * x1 - x3 ; ①
k 和 b 未知,公式①能否有解,就是简单的拓展欧几里得的 gcd 的利用了
总结反思 :
题目思路很清晰,但是 WA 了好几次,原因在于 int 类型数 与 long long 类型数 计算过程中 会出现未知错误,以前错过一次,这次记住!———— lxk
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn = 200 + 7;
int n;
LL a, m = 10001, x[maxn];
void gcd(LL a, LL b, LL &d, LL &x, LL &y) {
if(b == 0) {d = a; x = 1; y = 0;}
else { gcd(b, a%b, d, y, x); y -= x * (a/b); }
}
bool judge(LL c, LL b) {
for(int i = 2; i <= 2*n; ++i) {
if(i % 2) {
if(x[i] != (c * x[i-1] + b) % m) return false;
}
else x[i] = (c * x[i-1] + b) % m;
}
return true;
}
void print() {
for(int i = 2; i <= 2*n; i+=2)
cout << x[i] << endl;
}
void solve() {
for(a = 0; a < m; ++a) { // 枚举 a ;
LL k, b, d, c;
c = x[3] - a * a * x[1];
gcd(m, a+1, d, k, b);
if(c % d) continue;
b *= (c / d);
if(judge(a, b)) break;
}
print();
}
int main() {
// while(~scanf("%d", &n) && n) {
scanf("%d", &n);
for(int i = 1; i < 2*n; i += 2)
scanf("%lld", &x[i]);
solve();
// }
return 0;
}