HDU - 1005 Number Sequence (矩阵快速幂)
A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).
InputThe input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
OutputFor each test case, print the value of f(n) on a single line.
Sample Input
1 1 3 1 2 10 0 0 0
Sample Output
2 5
原谅博主不会Markdown
#include<iostream> #include<algorithm> #include<vector> #include<stack> #include<queue> #include<map> #include<set> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #define fuck(x) cout<<#x<<" = "<<x<<endl; #define debug(a,i) cout<<#a<<"["<<i<<"] = "<<a[i]<<endl; #define ls (t<<1) #define rs ((t<<1)|1) using namespace std; typedef long long ll; typedef unsigned long long ull; const int maxn = 100086; const int maxm = 100086; const int inf = 2.1e9; const ll Inf = 999999999999999999; const int mod = 7; const double eps = 1e-6; const double pi = acos(-1); struct Matrix{ int a[3][3]; }; Matrix mul(Matrix a,Matrix b){ Matrix ans; for(int i=1;i<=2;i++){ for(int j=1;j<=2;j++){ ans.a[i][j]=0; for(int k=1;k<=2;k++){ ans.a[i][j]+=a.a[i][k]*b.a[k][j]; } ans.a[i][j]%=mod; } } return ans; } Matrix q_pow(Matrix a,int b){ Matrix ans ; ans.a[1][1]=ans.a[2][2]=1; ans.a[2][1]=ans.a[1][2]=0; while (b){ if(b&1){ ans=mul(ans,a); } b>>=1; a=mul(a,a); } return ans; } int main() { // ios::sync_with_stdio(false); // freopen("in.txt","r",stdin); int A,B,n; while (scanf("%d%d%d",&A,&B,&n)!=EOF&&A&&B&&n){ Matrix exa; if(n<=2){printf("%d\n",1); continue; } exa.a[1][1]=A; exa.a[1][2]=B; exa.a[2][1]=1; exa.a[2][2]=0; exa=q_pow(exa,n-2); printf("%d\n",(exa.a[1][1]+exa.a[1][2])%7); } return 0; }
如需转载,请注明出处
如有侵权,联系删除
2290713181@qq.com
如有侵权,联系删除
2290713181@qq.com