题意
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).
思路
这道题如果初看,本想对7取余预处理,
但是一看数据太大,所以不好处理。
然后换个思路,可以打表找规律,这样可以行的通;
昨天刚学了矩阵连乘,所以用构造矩阵试做了一下~~AC,
现在附上代码:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
struct matrix //这是定义矩阵这种数据结构让下面可以使用它
{
int f[2][2];
};
matrix mul(matrix a,matrix b) //两矩阵相乘,矩阵乘法,用三层循环即可实现
{
matrix c;
memset(c.f,0,sizeof(c.f));
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
{
c.f[i][j]+=a.f[i][k]*b.f[k][j]; //加一个模一个,边乘边模~~~~~~
c.f[i][j]%=7;
}
return c;
}
matrix pow_mod(matrix a,int b) //矩阵快速幂运算
{
matrix s;
memset(s.f,0,sizeof(s.f));
s.f[0][0]=s.f[1][1]=1;
while(b)
{
if(b&1)
s=mul(s,a); //一个矩阵乘以单位矩阵还是他本身
a=mul(a,a);
b=b/2;
}
return s;
}
int main()
{
int a,b,n;
while(cin>>a>>b>>n)
{
if(a==0&&b==0&&n==0)break;
if(n==1||n==2)
{
cout<<1<<endl;
continue;
}
matrix e;
e.f[0][0]=a; e.f[0][1]=1;
e.f[1][0]=b; e.f[1][1]=0;
e=pow_mod(e,n-2);
cout<<(e.f[0][0]+e.f[1][0])%7<<endl;
}
return 0;
}