洛谷 P1939 【模板】矩阵加速(数列)
生活随笔
收集整理的這篇文章主要介紹了
洛谷 P1939 【模板】矩阵加速(数列)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
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。
輸出格式:
每行輸出一個非負整數表示答案。
輸入輸出樣例
輸入樣例#1: ?
3 6 8 10輸出樣例#1: ?
4 9 19說明
對于30%的數據 n<=100;
對于60%的數據 n<=2*10^7;
對于100%的數據 T<=100,n<=2*10^9;
題解:
其實這篇本來想寫日記的,但是老師突然來到了我的身邊,我就迅速把這道剛做完的題粘到了這里。
有始有終,就寫吧。
誰可以告訴我,為什么我的暴力沒有分!
眾人OS:你錯了唄。
#include <cstdio> #include <cstring> using namespace std;typedef long long LL; const int mod=1e9+7; int T, n; LL tmp[3][3]={{0,0,1},{1,0,0},{0,1,1}};struct Matrix33{LL mat[3][3];Matrix33 operator *(Matrix33 b){Matrix33 m;for (int i=0; i<3; ++i) for (int j=0; j<3; ++j){m.mat[i][j]=0;for (int k=0; k<3; ++k)m.mat[i][j]=(m.mat[i][j]+(mat[i][k]*b.mat[k][j]%mod))%mod;}return m;} }beg, unit, plus;Matrix33 get_mat(int n){memcpy(plus.mat, tmp, sizeof(tmp));Matrix33 ans=unit;while (n){if (n&1) ans=ans*plus;plus=plus*plus;n>>=1;}return ans; }int main(){unit.mat[0][0]=unit.mat[1][1]=unit.mat[2][2]=1;beg.mat[0][0]=beg.mat[0][1]=beg.mat[0][2]=1;scanf("%d", &T);for (int tt=0; tt<T; ++tt){scanf("%d", &n);if (n<4) printf("1\n");else printf("%lld\n", (beg*get_mat(n-3)).mat[0][2]);}return 0; } AC一世安寧
轉載于:https://www.cnblogs.com/GTBA/p/9441336.html
總結
以上是生活随笔為你收集整理的洛谷 P1939 【模板】矩阵加速(数列)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 英士顿电脑主机主板显示卡(英特尔显示卡)
- 下一篇: 使用shiro框架,注销问题的解决