有一个序列是这样定义的: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)的值。
Sample Input
3 -1 5
Sample Output
6
题解
:用矩阵快速幂即可
#include <iostream>
#include <vector>
#include <cstring>
#include <ctime>
#define pb push_back
using namespace std;
const int inf = 7;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
mat arrmul(mat A,mat B)
{
mat C;vec h;
for(ll i=0;i<A.size();i++)
{
for(ll j=0;j<B[0].size();j++)
h.pb(0);
C.pb(h);h.clear();
}
for(ll i=0;i<A.size();i++)
{
for(ll j=0;j<B[0].size();j++)
{
for(ll k=0;k<B.size();k++)
C[i][j]=(C[i][j]+A[i][k]*B[k][j]);
while(C[i][j]<0)C[i][j]+=inf;
C[i][j]%=inf;
}
}
return C;
}
ll zow(mat &A,mat &B,int n)
{
n=n-2;
while(n>0)
{
if(n&1)B=arrmul(A,B);
A=arrmul(A,A);
n>>=1;
}
return B[0][0];
}
int main()
{
ll a,b,n;
cin>>a>>b>>n;
mat A,B;vec m;
m.pb(a),m.pb(b);
A.pb(m);m.clear();
m.pb(1),m.pb(0);
A.pb(m);m.clear();
m.pb(1);
B.pb(m);m.clear();
m.pb(1);B.pb(m);//数据的输入
ll ans=zow(A,B,n);
cout<<ans<<endl;
return 0;
}