题目链接:http://acm.hdu.edu.cn/diy/contest_showproblem.php?cid=15840&pid=1002
这道题乍看是递推,实际上 n 就超过 int 型了,递推必定超时;
在 POJ 上的斐波那契一道题用的是矩阵的方法+二分,这道题也一样,不过矩阵可以构造成三阶的;
今天用 GNU C 挂了两题,%lld 不支持???最后都是用 VC 过的;
矩阵相乘的重复了,不敢用二维数组作形参,以前遇到这个问题卡得要死……麻烦就麻烦点吧。
# include <stdio.h> # include <string.h> typedef long long int LL; const LL MOD = 100000017; const LL A[3][3] = {{1,1,1}, {1,2,2}, {2,3,4}}; const LL C[3][3] = {{1,0,0}, {0,1,0}, {0,0,1}}; LL An[3][3]; LL a, b, c, n; void order(LL n) { int i, j, k, p; LL t[3][3], f[3][3]; memcpy(f, A, sizeof(A)); for (i = 0; i < 63; ++i) { if ((n>>i) & 0x1) { memcpy(t, An, sizeof(An)); for (j = 0; j < 3; ++j) for (k = 0; k < 3; ++k) { An[j][k] = 0; for (p = 0; p < 3; ++p) An[j][k] += t[j][p] * f[p][k]; An[j][k] %= MOD; } } memcpy(t, f, sizeof(f)); for (j = 0; j < 3; ++j) for (k = 0; k < 3; ++k) { f[j][k] = 0; for (p = 0; p < 3; ++p) f[j][k] += t[j][p] * t[p][k]; f[j][k] %= MOD; } } } int main() { int i; while (~scanf("%I64d%I64d%I64d%I64d", &a, &b, &c, &n)) { memcpy(An, C, sizeof(C)); order((n-1)/3); i = (n + 2) % 3; printf("%I64d\n", (An[i][0]*a+An[i][1]*b+An[i][2]*c) % MOD); } return 0; }
.