输入样例是
1 1 12 也就是第12个斐波那契数列,
原理是
f(n) = |1 1| * |f(n-2)|
f(n-1)= |1,0| * |f(n-1)|
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
struct ttt{
int map1[200][200];
};
int n;
ttt fun1(ttt &a,ttt &b){
ttt c;
int i,j,k;
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
c.map1[i][j]=0;
for(k=1;k<=n;k++)
c.map1[i][j]+=a.map1[i][k]*b.map1[k][j];
}
}
return c;
}
ttt fun2(ttt &a){
ttt b;
int i,j,k;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++){
b.map1[i][j]=0;
for(k=1;k<=n;k++)
b.map1[i][j]+=a.map1[i][k]*a.map1[k][j];
}
return b;
}
ttt pow1(ttt &a,int k){
ttt b;
int i,j;
memset(b.map1,0,sizeof(b.map1));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
b.map1[i][j]=1;
while(k){
//cout << "k=" <<k <<endl;
if(k&1)
b=fun1(b,a);
k=k>>1;
a=fun2(a);
}
return b;
}
int main(){
freopen("in.txt","r",stdin);
int i,j,k,l,f1,f2,f3,t1,t2,t3;
int r,c;
cin >>f1 >> f2>> k;
ttt a;
memset(a.map1,0,sizeof(a.map1));
n=2;
a.map1[1][1]=1;
a.map1[1][2]=1;
a.map1[2][1]=1;
a.map1[2][2]=0;
a=pow1(a,k-2);
/*for(i=1;i<=2;i++){
for(j=1;j<=2;j++)
cout << a.map1[i][j] << " ";
cout <<endl;
}*/
cout << a.map1[1][1]*f2+a.map1[1][2]*f1 <<endl;
return 0;
}
f(n)=b1*f(n-1)+a1*f(n-2)+c 输入 f1 f2 a1 b1 c1 n
例子
6 7 3 2 4 3
输出
37
代码:
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
struct ttt{
int map1[200][200];
};
int n;
ttt fun1(ttt &a,ttt &b){
ttt c;
int i,j,k;
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
c.map1[i][j]=0;
for(k=1;k<=n;k++)
c.map1[i][j]+=a.map1[i][k]*b.map1[k][j];
}
}
return c;
}
ttt fun2(ttt &a){
ttt b;
int i,j,k;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++){
b.map1[i][j]=0;
for(k=1;k<=n;k++)
b.map1[i][j]+=a.map1[i][k]*a.map1[k][j];
}
return b;
}
ttt pow1(ttt &a,int k){
ttt b;
int i,j;
memset(b.map1,0,sizeof(b.map1));
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
b.map1[i][j]=1;
while(k){
//cout << "k=" <<k <<endl;
if(k&1)
b=fun1(b,a);
k=k>>1;
a=fun2(a);
}
return b;
}
int main(){
freopen("in.txt","r",stdin);
int i,j,k,l,f1,f2,f3,t1,t2,t3;
int r,c;
int a1,b1,c1;
cin >>f2 >> f1>>b1>>a1>>c1>> k;
ttt a;
memset(a.map1,0,sizeof(a.map1));
n=3;
a.map1[1][1]=a1;
a.map1[1][2]=b1;
a.map1[1][3]=1;
a.map1[2][1]=1;
a.map1[2][2]=0;
a.map1[2][3]=0;
a.map1[3][1]=0;
a.map1[3][2]=0;
a.map1[3][3]=1;
a=pow1(a,k-2);
/*for(i=1;i<=3;i++){
for(j=1;j<=3;j++)
cout << a.map1[i][j] << " ";
cout <<endl;
}*/
cout << (a.map1[1][1]*f2)+(a.map1[1][2]*f1)+a.map1[1][3]*c1 <<endl;
return 0;
}