Without expecting, Angel replied quickly.She says: "I'v heard that you'r a very clever boy. So if you wanna me be your GF, you should solve
the problem called GF~. "
How good an opportunity that Gardon can not give up! The "Problem GF" told by Angel is actually "Gauss Fibonacci".
As we know ,Gauss is the famous mathematician who worked out the sum from 1 to 100 very quickly, and Fibonacci is the crazy man who
invented some numbers.
Arithmetic progression:
g(i)=k*i+b;
We assume k and b are both non-nagetive integers.
Fibonacci Numbers:
f(0)=0
f(1)=1
f(n)=f(n-1)+f(n-2) (n>=2)
The Gauss Fibonacci problem is described as follows:
Given k,b,n ,calculate the sum of every f(g(i)) for 0<=i<n
The answer may be very large, so you should divide this answer by M and just output the remainder instead.
输入格式
The input contains serveral lines. For each line there are four non-nagetive integers: k,b,n,M
Each of them will not exceed 1,000,000,000.
输出格式
For each line input, out the value described above.
样例输入
2 1 4 100 2 0 4 100
样例输出
21 12
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int M;
typedef long long int lint;
struct matrix {
int r,c;
lint a[5][5];
matrix() {}
matrix operator - (matrix b) {
for(int i=1; i<=r; i++) {
for(int j=1; j<=c; j++) {
b.a[i][j]=a[i][j]-b.a[i][j];
}
}
return b;
}
matrix operator + (matrix b) {
for(int i=1; i<=r; i++) {
for(int j=1; j<=c; j++) {
b.a[i][j]=a[i][j]+b.a[i][j];
}
}
return b;
}
matrix operator * (matrix m) {
matrix res;
if(c!=m.r) return res;
res.r=r;
res.c=m.c;
for(int i=1; i<=res.r; i++) {
for(int j=1; j<=res.c; j++) {
lint buf=0;
for(int k=1; k<=c; k++) {
buf+=a[i][k]*m.a[k][j];
buf%=M;
}
res.a[i][j]=buf;
}
}
return res;
}
matrix cut_matrix() {
matrix p;
p.r=p.c=r/2;
for(int i=1; i<=p.r; i++) {
for(int j=1; j<=p.c; j++) {
p.a[i][j]=a[i][j+p.r];
}
}
return p;
}
lint cut_num(void) {
return a[1][2];
}
void print(void) {
for(int i=1; i<=r; i++) {
for(int j=1; j<=c; j++) {
printf("%d ",a[i][j]);
}
printf("\n");
}
}
};
matrix id_producer(int n) {
matrix m;
m.r=m.c=n;
memset(m.a,0,sizeof(m.a));
for(int i=1; i<=n; i++) {
m.a[i][i]=1;
}
return m;
}
matrix B_matrix_producer(matrix b) {
matrix m;
m.r=2*b.r;
m.c=2*b.c;
int n=b.r;
memset(m.a,0,sizeof(m.a));
for(int i=1; i<=n; i++) {
m.a[i][i+n]=1;
m.a[i+n][i+n]=1;
for(int j=1; j<=n; j++) {
m.a[i][j]=b.a[i][j];
}
}
return m;
}
matrix pow(matrix A,int b) {
matrix id=id_producer(A.r);
while(b) {
if(b&1) {
id=id*A;
}
b>>=1;
A=A*A;
}
return id;
}
int main() {
int k,b,n;
while(scanf("%d %d %d %d",&k,&b,&n,&M)!=EOF) {
matrix base;
base.r=base.c=2;
base.a[1][2]=base.a[2][1]=base.a[2][2]=1;
base.a[1][1]=0;
matrix fb=pow(base,b);
matrix fk=pow(base,k);
matrix p=B_matrix_producer(fk);
p=pow(p,n);
matrix tr=p.cut_matrix();
matrix res=fb*tr;
printf("%lld\n",res.cut_num()%M);
}
return 0;
}