(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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值