模版 快速冪 矩陣快速冪

2021-10-01 10:55:25 字數 1568 閱讀 6286

原理:

x

yx^y

xy中的 y

yy 轉化成二進位制數,然後每乙個 1

11 對應 x

xx 的 i

ii 次方

這樣把x

yx^y

xy轉化成了x

yx^y

xy= x

ax^a

xa* x

bx^b

xb* x

cx^c

xc…通過對 x

xx 不斷翻倍的過程,來匹配y轉成二進位制的 111。

如果為 1

11 ,則記錄的答案就會乘 x

xx 的 相應次方。

p

pp 為模數

例題:luogu p1226 快速冪[模版]

luogu p2817 宋榮子的城堡

luogu p3197 越獄

int pow(int x, int y)

return ans;

}

矩陣相乘的條件:

矩陣 a

aa 有 n

nn 行 m

mm 列, 矩陣 b

bb 有 m

mm 行 p

pp 列 。

矩陣 c=a

∗b

c = a * b

c=a∗

b ,矩陣 c

cc 為 n

nn 行 p

pp 列。

n 、m

、p

n、m、p

n、m、

p 要滿足上述限制。

把矩陣當成乙個元素,重複上邊的普通的快速冪就好了。

注意:用結構體代表矩陣,二維陣列來儲存數字,過載結構體的 ∗

*∗ 運算。

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

using

namespace std;

long

long n, k, p =

1e9+7;

struct matrix

a,ans;

matrix operator*(

const matrix &x,

const matrix &y)

long

long

read()

while

(ch >=

'0'&& ch <=

'9')

return rt * in;

}int

main()

while

(k)for

(int i =

1; i <= n; i++

)system

("pause");

return0;

}

例題:[模版]矩陣快速冪

模版 矩陣快速冪

矩陣快速冪就是快速冪的矩陣用法 ll fast power ll fp a ll fp n ll fp p return ret 得到遞推公式後推出轉移矩陣然後就套模版啦 include include define mod 1000000009 define ll long long using ...

矩陣快速冪模版

const int n 10 int tmp n n void multi int a n int b n int n 上訴res陣列就等同於普通快速冪初始化的1,原理想通的,這個矩陣叫單位矩陣e,性質就是e a a,就是1 a a,一樣,單位矩陣就是對角線全是1其他全是0 最終算出的結果是乙個re...

快速冪(矩陣快速冪)

求 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 會超時,這裡引入快速冪來...