51nod 2级算法题-1126

来源:互联网 发布:约瑟夫环java链表实现 编辑:程序博客网 时间:2024/06/07 08:25

1126 求递推序列的第N项

有一个序列是这样定义的:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.给出A,B和N,求f(n)的值。

Input

输入3个数:A,B,N。数字之间用空格分割。(-10000 <= A, B <= 10000, 1 <= N <= 10^9)

Output

输出f(n)的值。

Input示例

3 -1 5

Output示例

6

找Fibonacci数列循环节。一般情况下,类Fibonacci 数组在Mod^2内一定出现循环节。在数据水的情况下,就不需要快速幂了。

#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <cstdlib>#include <cmath>#include <algorithm>#include <queue>#include <stack>using namespace std;#define endl "\n"const int maxn=100000000;const int MOD=7;int F[300];int main (){    int a,b,n;    cin>>a>>b>>n;    if (n== 1 || n==2){        printf("1\n");        return 0;    }    F[0]=1;    F[1]=1;    F[2]=1;    int i;    for(i=3;i<300;i++){        F[i]=((a*F[i-1]+b*F[i-2])%MOD+MOD)%MOD;        if(F[i]==1 &&F[i-1]==1){            break;        }    }    F[0]=F[i-2];    n%=(i-2);    cout<<F[n]<<endl;    return 0;}
0 0