Count(hdu 6470 矩阵快速幂 含关于n的多项式)

题目链接:

hdu 6470 Count

 

题意:

f[n] = 2*f[n-2] + f[n-1] + n^3,n<=1e18,求f[n] 。

 

思路:

在计算 f[n+1] 的时候,n^{3} 要变为 (n+1)^{3} = n^{3}+3n^{2}+3n+1,所以构造的矩阵中需要有这几项,然后因为引入了 n^{2} ,所以3n^{2} 要变为 3(n+1)^{2} = 3n^{2}+6n+3 ,因为 n^{2} 项、n项、常数项都已经存在,所以不需要引入新的项,其余各项均可通过这几项计算出。因此,构造的矩阵为:

[f[2],f[1],3^{3},3*3^{2},3*3,1] * \begin{bmatrix} 1 & 1 & 0 & 0 & 0 & 0\\ 2& 0 & 0 & 0 & 0 & 0\\ 1& 0 & 1 & 0 & 0 & 0\\ 0 & 0 & 1 & 1 & 0 & 0\\ 0 & 0 & 1 & 2 & 1 & 0\\ 0& 0 & 1 & 3 & 3 & 1 \end{bmatrix} 。

使用矩阵快速幂求解即可。

 

Code:

#include
using namespace std;

typedef long long ll;

const int MAX = 1e6 + 20;
const int mod = 123456789;

ll n;

typedef struct {
	ll m[10][10];
}Matrix;

Matrix Mul(Matrix a, Matrix b)
{
	Matrix c;
	memset(c.m, 0, sizeof(c.m));
	for (int i = 0; i < 6; i++)
	{
		for (int j = 0; j < 6; j++)
		{
			for (int k = 0; k < 6; k++)
			{
				c.m[i][j] += ((a.m[i][k] * b.m[k][j]) % mod + mod) % mod;
				c.m[i][j] %= mod;
			}
		}
	}
	return c;
}

Matrix fastm(Matrix a, ll num)
{
	Matrix res;
	memset(res.m, 0, sizeof(res.m));
	for (int i = 0; i < 6; i++)
		res.m[i][i] = 1;
	while (num)
	{
		if (num & 1)
			res = Mul(res, a);
		num >>= 1;
		a = Mul(a, a);
	}
	return res;
}

int main()
{
	int T;
	scanf("%d", &T);
	Matrix a;
	memset(a.m, 0, sizeof(a.m));
	a.m[0][0] = 1, a.m[0][1] = 1;
	a.m[1][0] = 2;
	a.m[2][0] = 1, a.m[2][2] = 1;
	a.m[3][2] = 1, a.m[3][3] = 1;
	a.m[4][2] = 1, a.m[4][3] = 2, a.m[4][4] = 1;
	a.m[5][2] = 1, a.m[5][3] = 3, a.m[5][4] = 3, a.m[5][5] = 1;
	ll st[10];
	st[0] = 2, st[1] = 1, st[2] = 27, st[3] = 27, st[4] = 9, st[5] = 1;
	while (T--)
	{
		scanf("%lld", &n);
		n -= 2;
		Matrix b = fastm(a, n);
		ll ans = 0;
		for (int i = 0; i < 6; i++) {
			ans = (ans + b.m[i][0] * st[i] % mod) % mod;
		}
		printf("%lld\n", ans);
	}
	return 0;
}

 

你可能感兴趣的:(ACM-矩阵快速幂)