【模板】矩阵加速(数列) 矩阵快速幂
题目描述
a[1]=a[2]=a[3]=1
a[x]=a[x-3]+a[x-1] (x>3)
求a数列的第n项对1000000007(10^9+7)取余的值。
输入输出格式
输入格式:第一行一个整数T,表示询问个数。
以下T行,每行一个正整数n。
输出格式:每行输出一个非负整数表示答案。
输入输出样例
说明
对于30%的数据 n<=100;
对于60%的数据 n<=2*10^7;
对于100%的数据 T<=100,n<=2*10^9;
#include<iostream> #include<cstdio> #include<algorithm> #include<cstdlib> #include<cstring> #include<string> #include<cmath> #include<map> #include<set> #include<vector> #include<queue> #include<bitset> #include<ctime> #include<time.h> #include<deque> #include<stack> #include<functional> #include<sstream> //#include<cctype> //#pragma GCC optimize(2) using namespace std; #define maxn 200005 #define inf 0x7fffffff //#define INF 1e18 #define rdint(x) scanf("%d",&x) #define rdllt(x) scanf("%lld",&x) #define rdult(x) scanf("%lu",&x) #define rdlf(x) scanf("%lf",&x) #define rdstr(x) scanf("%s",x) #define mclr(x,a) memset((x),a,sizeof(x)) typedef long long ll; typedef unsigned long long ull; typedef unsigned int U; #define ms(x) memset((x),0,sizeof(x)) const long long int mod = 1e9 + 7; #define Mod 1000000000 #define sq(x) (x)*(x) #define eps 1e-5 typedef pair<int, int> pii; #define pi acos(-1.0) //const int N = 1005; #define REP(i,n) for(int i=0;i<(n);i++) typedef pair<int, int> pii; inline int rd() { int x = 0; char c = getchar(); bool f = false; while (!isdigit(c)) { if (c == '-') f = true; c = getchar(); } while (isdigit(c)) { x = (x << 1) + (x << 3) + (c ^ 48); c = getchar(); } return f ? -x : x; } ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a%b); } int sqr(int x) { return x * x; } /*ll ans; ll exgcd(ll a, ll b, ll &x, ll &y) { if (!b) { x = 1; y = 0; return a; } ans = exgcd(b, a%b, x, y); ll t = x; x = y; y = t - a / b * y; return ans; } */ struct Mat { int a[5][5]; void init() { ms(a); for (int i = 0; i < 5; i++)a[i][i] = 1; } }; Mat mul(Mat a, Mat b) { Mat ans; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { ans.a[i][j] = 0; for (int k = 0; k < 5; k++) { ans.a[i][j] = (ans.a[i][j] + a.a[i][k] % mod*b.a[k][j] % mod) % mod; ans.a[i][j] %= mod; } } } return ans; } Mat qpow(Mat a, int n) { Mat ans; ans.init(); while (n) { if (n & 1)ans = mul(ans, a); a = mul(a, a); n >>= 1; } return ans; } int main() { // ios::sync_with_stdio(0); int T = rd(); while (T--) { int n = rd(); if (n == 1 || n == 2 || n == 3)cout << 1 << endl; else { Mat tmp; ms(tmp.a); tmp.a[0][0] = 1; tmp.a[0][2] = 1; tmp.a[1][0] = 1; tmp.a[2][1] = 1; tmp = qpow(tmp, n - 3); ll ans = (1ll * tmp.a[0][0] % mod + 1ll * tmp.a[0][1] % mod + 1ll * tmp.a[0][2] % mod) % mod; printf("%lld\n", ans%mod); } } return 0; }
EPFL - Fighting