1. 程式人生 > >快速冪(2)

快速冪(2)

連結:https://ac.nowcoder.com/acm/contest/221/C
來源:牛客網

令f(n)=2*f(n-1)+3*f(n-2)+n,f(1)=1,f(2)=2
令g(n)=g(n-1)+f(n)+n*n,g(1)=2
告訴你n,輸出g(n)的結果,結果對1e9+7取模

輸入描述:

多組輸入,每行一個整數n(1<=n<=1e9),如果輸入為0,停止程式。

輸出描述:

在一行中輸出對應g(n)的值,結果對1e9+7取模。

示例1

輸入

複製
1
5
9
456
0

輸出

複製
2
193
11956
634021561

說明

多組輸入,輸入為0時,終止程式

備註:

項數極大,樸素演算法無法在規定時間內得出結果


PS:快速冪的一般形式為B`=A^N*B(其中B`和B的形式是一樣的,只是下標相差1)

B`和B、A都是n階方陣


 
 
 
#include <iostream>
#include<string.h>
#include<stdio.h>
#define ll long long
using
namespace std; const ll mod = 1000000007; struct mat { ll m[6][6]; mat() { memset(m, 0, sizeof(m)); } }; mat mul(mat &A, mat &B) { mat C; 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]
= (C.m[i][j] + A.m[i][k] * B.m[k][j]) % mod; } } } return C; } mat pow(mat A, ll n) { mat B; B.m[0][0] = 8; B.m[1][0] = 10; B.m[2][0] = 2; B.m[3][0] = 9; B.m[4][0] = 3; B.m[5][0] = 1; while (n) { if (n & 1) B = mul(A, B); A = mul(A, A); n >>= 1; } return B; } int main() { ll n; while (cin >> n&&n!=0) { mat A; A.m[0][0] = A.m[0][1]= A.m[0][3]=1; A.m[1][1] = 2;A.m[1][2]=3;A.m[1][4]=A.m[1][5]=1; A.m[2][1] = 1; A.m[3][3]=1;A.m[3][4]=2;A.m[3][5]=1; A.m[4][4] = A.m[4][5]=1; A.m[5][5] = 1; if(n==1) cout<<2<<endl; else if(n==2) cout<<8<<endl; else { mat B = pow(A, n-2); printf("%lld\n", B.m[0][0]); } } return 0; }