题目链接:HDU 2855
题目大意:给出你公式,让你求( 求和C(k,n)F(k) )%m ,F(0) = 0; F(1) = 1; F(n) = F(n-1)+F(n-2); (斐波那契数列)
分析:
不会,这个老哥写的挺详细的:
点我传送
设矩阵 A = |1 1|
|1 0|
设矩阵 B = (A^n)
则B[0][0] = F(n-1); B[0][1] = B[1][0] = F(n); B[1][1] = F(n-1);
{ 注:上述为斐波那契矩阵的性质 }
令D = ( C[n][0]*(A^0) + C[n][1]*(A^1) +...+ C[n][k]*(A^k) ) % m = ( (A + E)^n ) % m (E为单位阵)
{ 类比二次多项式(x+1)^n = C[n][0]+C[n][0]*x+...+C[n][k]*(x^k) }
则D[1][0]或D[0][1]即为所求
以下是代码
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define Fi first
#define Se second
#define ll long long
#define inf 0x3f3f3f3f
#define lowbit(x) (x&-x)
#define PLL pair<ll,ll>
#define PII pair<int,int>
#define l_inf 0x3f3f3f3f3f3f3f
#define mmin(a,b,c) min(a,min(b,c))
#define mmax(a,b,c) max(a,max(b,c))
#define debug(a) cout<<#a<<"="<<a<<endl;
#define Sc_P(x) scanf("%d%d",&x.Fi,&x.Se)
#define Sc_PL(x) scanf("%lld%lld",&x.Fi,&x.Se)
#define debug2(a,b) cout<<#a<<"="<<a<<" "<<#b<<"="<<b<<endl;
using namespace std;
const int N=3e5+10;
const int maxn=10;
ll Mod;
ll tmp[maxn][maxn];
void multi(ll a[][maxn],ll b[][maxn],int n)//n是矩阵大小
{
int i,j,k;
memset(tmp,0,sizeof tmp);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
for(k=1;k<=n;k++)
{
tmp[i][j]+=a[i][k]*b[k][j];
tmp[i][j]%=Mod;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=tmp[i][j];
}
ll res[maxn][maxn];
void Pow(ll a[][maxn],ll m,int n)// a 是初始矩阵 res是答案数组 m是幂,n是矩阵大小
{
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
res[i][j]=(i==j);
while(m)
{
if(m&1) multi(res,a,n); //res=res*a;
multi(a,a,n); //a=a*a
m>>=1;
}
}
void Show(int n,ll res[][maxn])
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<res[i][j]<<" ";
}
cout<<endl;
}
}
ll a[maxn][maxn];
int main()
{
int T;scanf("%d",&T);
ll n;
while(T--)
{
scanf("%lld%lld",&n,&Mod);
a[1][1]=2;a[1][2]=1;
a[2][1]=1;a[2][2]=1;
Pow(a,n,2);
printf("%lld\n",res[1][2]);
}
return 0;
}
/*
f[i]=2f[i-1]+f[i-2]
f[i-1]=f[i-]+f[i-2]
*/