基准时间限制:1 秒 空间限制:131072 KB 分值: 10
难度:2级算法题
有一个序列是这样定义的: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
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int mod=7; struct mx { LL a[2][2]; }; mx solve(mx a,mx b) { mx c; for(int i=0; i<2; i++) for(int j=0; j<2; j++) { c.a[i][j]=0; for(int k=0; k<2; k++) { c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod; } } return c; } mx qpow(mx t,LL n) { mx ans; ans.a[0][0]=ans.a[1][1]=1; ans.a[0][1]=ans.a[1][0]=0; while(n) { if(n&1) ans=solve(ans,t); n>>=1; t=solve(t,t); } return ans; } int main() { LL a,b,n; scanf("%lld%lld%lld",&a,&b,&n); if(n==1||n==2) printf("1\n"); else { mx t={(a%7+7)%7,(b%7+7)%7,1,0}; mx ans=qpow(t,n-2); t={1,0,1,0}; //t={f[2],0,f[1],0}!!!!! ans=solve(ans,t); printf("%lld\n",ans.a[0][0]); } return 0; }