本文主要是介绍(2016弱校联盟十一专场10.5) F. Fibonacci of Fibonacci (暴力 + 循环节),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
The math class is coming again. You can’t wait to tell Nozomi the game “Knight Garden”, and she return
a puzzle called “Fibonacci of Fibonacci” back to you.
We are all familiar with Fibonacci sequence, which can defined by the recurrence relation as follows.
F 0 = 0
F 1 = 1
F n = F n−1 + F n−2
Since calculating F n mod 20160519 is too boring for you, she is asking you to calculate F F n mod 20160519.
Input
The first line contains an integer T .
Each of the following T lines contains an integer n in a single line.
• 1 ≤ T ≤ 10000
• 1 ≤ n ≤ 10^9
Output
For each test case, output an integer F F n mod 20160519 in a single line.
Examples
standard input
2
5
6
standard output
5
21
题意:
F(n)表示斐波那契数列的第n项,求F(F(n))%mod的值。(1<=n<=10^9) 由于mod是10^7级别的数,因此可以离线暴力打表求斐波那契数列F(n)%mod的循环节。
#include <bits/stdc++.h>
using namespace std;
const int mod = 20160519;
const int maxn = 1e8;
int f[maxn];
int main(){f[0] = 0; f[1] = 1;for(int i = 2; i; i++){f[i] = (f[i-1]+f[i-2])%mod;if(f[i] == f[1] && f[i-1] == f[0]){printf("T = %d\n", i-1);break;}}return 0;
}
由上述代码可知,G(x) = F(x) % mod的周期T = 26880696。
因此题目所求的K(x) = F(F(x))%mod = F(F(x)%T)%mod。
令U(x) = F(x)%T,然后考虑枚举x,再次暴力打表寻找函数U(x)的循环节。
#include <bits/stdc++.h>
using namespace std;
const int mod = 20160519;
const int maxn = 1e8;
int T;
int f[maxn], fi[maxn], ff[maxn];
int main(){f[0] = 0; f[1] = 1;for(int i = 2; i; i++){f[i] = (f[i-1]+f[i-2])%mod;if(f[i] == f[1] && f[i-1] == f[0]){T = i-1;printf("T = %d\n", i-1);break;}}fi[0] = 0; fi[1] = 1;for(int i = 2; i; i++){fi[i] = (fi[i-1]+fi[i-2])%T;if(fi[i] == fi[1] && fi[i-1] == fi[0]){printf("t = %d\n", i-1);break;}}return 0;
}
可得,函数U(x) = F(x) % T的周期t = 746688。
由于函数U(x)为所求函数K(x)的自变量,其自变量的周期为t,故函数K(x)的周期为t。
所以对于任意一个n,f(f(n) % mod = f(f(n % t) % T) % mod;
因此可以预处理出所有的fi[x] = fibonacci[x] % mod, 以及f[x] = fibonacci[x] % T。
则对于任意n(1 <= n <= 1e9),则有f(f(x)) % mod = fi[f[x % t]]。
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e7;
const int mod = 20160519;
const int rnd = 26880696;
const int cnt = 746688;
int f[maxn], fi[maxn], ff[maxn];
inline void init(){f[0] = 0; f[1] = 1; f[2] = 1;fi[0] = 0; fi[1] = 1; fi[2] = 1;for(int i = 3; i <= rnd; i++){f[i] = (f[i-1] + f[i-2]) % rnd;fi[i] = (fi[i-1] + fi[i-2]) % mod;}
}
int main(){int t, n;init();cin >> t;while(t--){scanf("%d", &n);printf("%d\n", fi[f[n%cnt]]);}return 0;
}
这篇关于(2016弱校联盟十一专场10.5) F. Fibonacci of Fibonacci (暴力 + 循环节)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!