题意:求s
s = g(g(g(n))) mod 1000000007
其中g(n)
g(n) = 3g(n - 1) + g(n - 2)
g(1) = 1
g(0) = 0
题解:普通的矩阵快速幂会超时,看到别人的题解是需要计算循环节得到小的MOD从而减小计算量。1000000007太大,需要计算更小的一个循环节,新技能get。
#include <stdio.h>
#include <string.h>
struct Mat {
long long g[3][3];
}ori, res;
long long n, MOD;
Mat multiply(Mat x, Mat y) {
Mat temp;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++) {
temp.g[i][j] = 0;
for (int k = 0; k < 2; k++)
temp.g[i][j] = (temp.g[i][j] + x.g[i][k] * y.g[k][j]) % MOD;
}
return temp;
}
void calc(long long n) {
while (n) {
if (n & 1)
ori = multiply(ori, res);
n >>= 1;
res = multiply(res, res);
}
}
int main() {
/* 求循环节
long long a = 0, b = 1;
for (int i = 2;;i++) {
a = (b * 3 + a) % 1000000007;
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("%lld %lld\n", a, b);
if (a == 0 && b == 1)
printf("%d\n", i);
}
i - 1 = 即为循环节
*/
while (scanf("%lld", &n) == 1) {
if (n == 0) {
printf("0\n");
continue;
}
if (n == 1) {
printf("1\n");
continue;
}
res.g[0][0] = 3; res.g[1][0] = res.g[0][1] = 1; res.g[1][1] = 0;
ori.g[0][0] = 1; ori.g[1][0] = ori.g[0][1] = ori.g[1][1] = 0;
MOD = (long long)183120; //g(g(g(n))) = g(g(y)) 那么183120是y的循环节
calc(n - 1);
n = ori.g[0][0];
if (n != 0 && n != 1) {
res.g[0][0] = 3; res.g[1][0] = res.g[0][1] = 1; res.g[1][1] = 0;
ori.g[0][0] = 1; ori.g[1][0] = ori.g[0][1] = ori.g[1][1] = 0;
MOD = (long long)222222224; //g(g(g(n))) = g(x) 那么222222224是x的循环节
calc(n - 1);
n = ori.g[0][0];
}
if (n != 0 && n != 1) {
res.g[0][0] = 3; res.g[1][0] = res.g[0][1] = 1; res.g[1][1] = 0;
ori.g[0][0] = 1; ori.g[1][0] = ori.g[0][1] = ori.g[1][1] = 0;
MOD = (long long)1000000007;
calc(n - 1);
}
printf("%lld\n", ori.g[0][0]);
}
return 0;
}
时间: 2024-10-08 11:13:02