矩陣快速冪用於解決快速求線性遞推關係f(n) = a1*f(n-1) + a2*f(n-2) + a3*f(n-3) + ...+ ad*f(n-d)中的項f(n);
具體方法;
令f(n) = [ f(n-d+1), f(n-d+2),,,,,,f(n)]; //注意此處f(n)看做d行1列的矩陣
則可以構造乙個矩陣c[d][d],使得f(n) = c*f(n-1);
那麼f(n) = c^(n-d)*f(d);
其中a的構造方法為:
memset(c,0,sizeof(c));
for (int i=0; i=0; i--,j++) c[d-1][i] = a[j];
矩陣快速冪模板:
矩陣快速冪求void mul_matrix(int x[max][max], int y[max][max], int d)
memcpy(c,u,sizeof(u));
}
fibonacci
poj3070
#include#include#include#include#include#include#include#include#include#include#include#include#include#include#define ll long long
#define max 10
#define inf int_max
#define eps 1e-8
#define mod 10000
using namespace std;
int a[max][max],b[max][max];
void mul_matrix(int x[max][max], int y[max][max], int d)
memcpy(c,u,sizeof(u));
}int main()
if (n == 1)
int res[2],f = ; //結果矩陣,最終結果儲存在為res[d-1]; 注意此處res,f = 看做2行1列的矩陣,其中1,1分別為數列的前兩項
pow_matrix(c,2,n-2);
for (int i=0; i<2; i++)
printf("%d\n",res[1] % mod);
} return 0;
}
快速冪(矩陣快速冪)
求 3 0 3 1 3 n mod 1000000007 input 輸入乙個數n 0 n 10 9 output 輸出 計算結果 sample input 3sample output 40 分析 利用等比數列的求和公式得所求和是 3 n 1 1 2,如果暴力求3 n 1 會超時,這裡引入快速冪來...
快速冪 矩陣快速冪
快速冪 正常情況下求乙個數的冪時間複雜度為o n 而快速冪能把時間複雜度降到o logn 舉個例子 求5的13次方 思想首先把13化為二進位制 1101,即13 1101 8 1 4 1 2 0 1 1 即5 13 58 1 54 1 52 0 5 1 15 5 8 1 5 4 1 5 2 0 5 ...
快速冪 矩陣快速冪
快速冪 我們求a ba b ab最直接的方法就是把a乘b次這樣的話複雜度就是o n o n o n 但是在比賽時面對1e9的資料時還是會輕鬆超時的,此時就需要一種更快的乘法來幫助我們 我們把b拆成二進位制的形式得到a ba b ab a 10.01 a a1 0.01此時對b分解得到的序列10.01...