[Luogu 1939] Fast Power linear recursion matrix +

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/giftedpanda/article/details/100896190

topic:a_n = a_{n-1} + a_{n-3},\ a_1 = a_2 = a_3 = 1

I do not know why this afternoon matrix fast power top.

Meaning of the questions:

a_n = a_{n-1} + a_{n-3}

We just need to find  \left[ \begin{matrix} a_{n-1} & a_{n-2} & a_{n-3} \end{matrix} \right ] the  \left[ \begin{matrix} a_n&a_{n-1} &a_{n-2} \end{matrix} \right ]linear recurrence relation to the.

We can obtain the following three linear equations

a_n = 1 * a_{n-1} + 0 * a_{n-2} + 1 * a_{n-3}

a_{n-1} = 1 * a_{n-1} + 0 * a_{n-2} + 0 * a_{n-3}

a_{n-2} = 0 * a_{n-1} + 1 * a_{n-2} + 0 * a_{n-3}

then

\[ \begin{matrix} a_{n-1}&a_{n-2}&a_{n-3} \end{matrix} \] \left\[ \begin{matrix} 1 & 1 & 0\\ 0 & 0 & 1\\ 1 & 0 & 0\\ \end{matrix} \right] = \left\[\ \begin{matrix} a_{n} & a_{n-1} & a_{n-2} \end{matrix} \right]

Finally, we can use the power of the matrix quickly solved.

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
struct matrix {
	ll a[4][4];
	matrix() {
		memset(a, 0, sizeof(a));
	}
	matrix operator * (const matrix& b) {
		matrix res;
		for(int i = 1; i <= 3; i++) {
			for(int j = 1; j <= 3; j++) {
				for(int k = 1; k <= 3; k++) {
					res.a[i][j] = (res.a[i][j] % mod + a[i][k] % mod * b.a[k][j] % mod + mod) % mod;
				}
			}
		}
		return res;
	}
};
ll power(ll n)
{
	matrix ans, base;
	for(int i = 1; i <= 3; i++) {
		for(int j = 1; j <= 3; j++) {
			ans. a[i][j] = base.a[i][j] = 0;
		}
	}
	ans.a[1][1] = ans.a[1][2] = ans.a[1][3] = 1;
	base.a[1][1] = base.a[1][2] = 1;
	base.a[2][3] = 1;
	base.a[3][1] = 1;
	while(n) {
		if(n & 1) ans = ans * base;
		base = base * base;
		n >>= 1;
	}
	return ans.a[1][1];
}
int main()
{
	int t;
	ll n;
	scanf("%d", &t);
	while(t--) {
		scanf("%lld", &n);
		if(n == 1 || n == 2 || n == 3) printf("1\n");
		else printf("%lld\n", power(n-3));
	}

}

 

Guess you like

Origin blog.csdn.net/giftedpanda/article/details/100896190