HDU 1005 Number Sequence 矩阵快速幂
Posted bethebestone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 1005 Number Sequence 矩阵快速幂相关的知识,希望对你有一定的参考价值。
Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 236241 Accepted Submission(s): 60070
Problem Description
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).
Input
The 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.
Output
For 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
解题思路:
就是一个简单的矩阵快速幂的模板题,推出他的传递矩阵是
{ A,B,
1, 0};
然后再套用矩阵快速幂的模板即可,注意当询问为n的时候,要求幂的次数是n-2次
代码如下:
#include<iostream> #include<cstdio> #include<cstring> #define mem(a) memset(a,0,sizeof(a)) #define forn(i,n) for(int i=0;i<n;++i) #define for1(i,n) for(int i=1;i<=n;++i) #define IO std::ios::sync_with_stdio(false); std::cin.tie(0) using namespace std; typedef long long ll; const int maxn=30; const int mod=7; const int inf=0x3f3f3f3f; int n,m,k,t,x,y; struct Matrix { int val[2][2]; }; Matrix E= {1,0, 0,1 }; Matrix Multiply(Matrix a,Matrix b) { Matrix ans=E; forn(i,2) forn(j,2) { int temp=0; forn(k,2) temp=(temp+a.val[i][k]*b.val[k][j]%mod)%mod; ans.val[i][j]=temp; } return ans; } int quick_pow(Matrix a,int n) { Matrix res=E; while(n>0) { if(n&1) res=Multiply(res,a); a=Multiply(a,a); n>>=1; } int ans=0; ans=(res.val[0][0]+res.val[0][1])%mod; return ans; } int main(){ IO; while(cin>>x>>y>>n) { if(x==y&&n==x&&x==0) break; Matrix t= { x,y, 1,0 }; int ans=(quick_pow(t,n-2))%mod; cout<<ans<<endl; } return 0; }
以上是关于HDU 1005 Number Sequence 矩阵快速幂的主要内容,如果未能解决你的问题,请参考以下文章