1304. 佳佳的斐波那契
题意:
S(n)表示Fibonacci的前n项和mod m
T(n)=(F1+2F2+3F3+…+nFn)mod m
给n和m,求T(n)
题解:
矩阵快速幂
参考题解
关键在于构造矩阵相乘的形式
代码:
#include<bits/stdc++.h>
#define debug(a,b) printf("%s = %d\n",a,b)
typedef long long ll;
using namespace std;inline int read(){int s=0,w=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();//s=(s<<3)+(s<<1)+(ch^48);return s*w;
}
ll a[4][4]={{0,1,1,0},{1,1,1,0},{0,0,1,1},{0,0,0,1}
};
ll x[4][4]={{0,1,1,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}
};
ll n,m;
void mul(ll a[4][4],ll b[4][4])
{ll ans[4][4]={0};for(int i=0;i<4;i++){for(int j=0;j<4;j++){for(int k=0;k<4;k++)ans[i][j]+=a[i][k]*b[k][j]%m;}} for(int i=0;i<4;i++)for(int j=0;j<4;j++)a[i][j]=ans[i][j]%m;
}
void mul_pow(int n)
{while(n){if(n&1)mul(x,a);mul(a,a);n>>=1;}
}
int main()
{cin>>n>>m;mul_pow(n-1);printf("%lld",((n*x[0][2]-x[0][3])%m+m)%m);return 0;
}