Reading comprehension HDU - 4990

原题链接
考察:矩阵快速幂
fw本f,想到了把f[i-1]拆开,但没想到只拆一个啊!!!
思路:

\[f[i] = 2 \times f[i-1]+1\qquad(i为奇数) \]

\[f[i] = f[i-1] + 2 \times f[i-2] +1 \]

\[f[i] = 2 \times f[i-1] \qquad (i为偶数) \]

\[f[i] = f[i-1] + 2 \times f[i-2]+1 \]

Code

#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 3; 
int n,m;
void mul(int f[],int a[][N])
{
	int res[N] = {0};
	for(int i=0;i<N;i++)
	  for(int j=0;j<N;j++)
	    res[i] = (res[i]+(LL)f[j]*a[j][i])%m;
	memcpy(f,res,sizeof res);
}
void mul(int a[][N])
{
	int res[N][N] = {0};
	for(int i=0;i<N;i++)
	  for(int j=0;j<N;j++)
	   for(int k=0;k<N;k++)
	     res[i][j] = (res[i][j]+(LL)a[i][k]*a[k][j])%m;
	memcpy(a,res,sizeof res);
}
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		int f[N] = {1,0,1};
		int a[N][N] = {
	   		{1,1,0},
	   		{2,0,0},
	   		{1,0,1}
		};
		while(n)
		{
			if(n&1) mul(f,a);
			mul(a);
			n>>=1;
		}
		printf("%d\n",f[1]);
	}
	return 0;
}
posted @ 2021-06-07 12:19  acmloser  阅读(26)  评论(0编辑  收藏  举报