题目链接:点击打开链接
题意:有一个序列是这样定义的:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
给出A,B和N,求f(n)的值。
分析:递推式,和简单的库镇快速幂:
代码如下:
#include <set>
#include <queue>
#include <math.h>
#include <vector>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <algorithm>
using namespace std;
struct Matrix{
int m[2][2];
}ter;
Matrix muli(Matrix A,Matrix B){
Matrix ans;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++){
ans.m[i][j]=0;
for(int k=0;k<2;k++){
ans.m[i][j]+=A.m[i][k]*B.m[k][j];
ans.m[i][j]%=7;
}
}
return ans;
}//矩阵乘法
Matrix quick_mod(Matrix a,int b){
Matrix ans=ter;
while(b){
if(b&1){
ans=muli(ans,a);
b--;
}
else {
b>>=1;
a=muli(a,a);
}
}
return ans;
}
int main(){
Matrix A,B;
int a,b,n;
scanf("%d%d%d",&a,&b,&n);
if(n==1){
puts("1");
return 0;
}
if(n==2){
puts("1");
return 0;
}
while(a<0)
a+=7;
while(b<0)
b+=7;
n-=2;
ter.m[0][0]=ter.m[1][1]=1;
ter.m[0][1]=ter.m[1][0]=0;
A.m[0][0]=0;
A.m[0][1]=b;
A.m[1][0]=1;
A.m[1][1]=a;//初始化矩阵
A=quick_mod(A,n);
B.m[0][0]=1;
B.m[0][1]=1;
B.m[1][0]=0;
B.m[1][1]=0;
B=muli(B,A);
printf("%d\n",B.m[0][1]);
return 0;
}