P1939(矩阵快速幂)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43475173/article/details/101100837

题目

模板题,用矩阵加速这种类斐波那契数列

题解

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define ll long long
const ll M=1000000007;
struct Matrix
{
	ll m[20][20];
};
Matrix t;
Matrix cheng(Matrix a,Matrix b,int m1)
{
	Matrix c;
	int i,j,k,m=3;
	for(i=1;i<=m;i++)
	{
		for(j=1;j<=m;j++)
		{
			c.m[i][j]=0;
		}
	}
	for(i=1;i<=m;i++)
	{
		for(k=1;k<=m;k++)
		{
			if(a.m[i][k]==0) continue;
			for(j=1;j<=m1;j++)
			{
			c.m[i][j]=(c.m[i][j]+a.m[i][k]*b.m[k][j])%M;
			}
		}
	}
	return c;
}
Matrix eye()
{
	int i,j;
	int m=3;
	Matrix a;
	for(i=1;i<=m;i++)
	{
		for(j=1;j<=m;j++)
		{
			if(i==j)
			a.m[i][j]=1;
			else
			a.m[i][j]=0;
		}
	}
	return a;
}
Matrix kuaisu(Matrix a,int k)
{
	Matrix ans,res;
	ans=eye();
	res=a;
	while(k)
	{
		if(k&1)
		{
			ans=cheng(ans,res,3);
		}
		res=cheng(res,res,3);
		k=k>>1;
	}
	return ans;
}
int main()
{
	int T,n,m1,m2,m;
	scanf("%d",&T);
	ll ans;Matrix b;Matrix c;
	c.m[1][1]=1;c.m[2][1]=1;c.m[3][1]=1;
	t.m[1][1]=1;t.m[1][3]=1;t.m[2][1]=1;t.m[3][2]=1;
	for(int i=1;i<=T;i++){
		scanf("%d",&m);
		if(m<=3){
			ans=1;
		}
		else{
			b=kuaisu(t,m-3);
			/*for(int i=1;i<=3;i++){
				for(int j=1;j<=3;j++){
					cout<<b.m[i][j]<<' ';
				}
				cout<<endl;
			}*/
			b=cheng(b,c,1);
			ans=b.m[1][1];
		}
		cout<<ans<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_43475173/article/details/101100837
今日推荐