国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

矩陣快速冪 非詳解

2019-11-14 08:43:50
字體:
供稿:網(wǎng)友
#include <cstdio>#include <cstring>int n, k;const int mod = 9973;struct matrix{ int tr[10][10]; matrix Operator * (const matrix &a) const{//重載運(yùn)算符 matrix tmp; memset(tmp.tr, 0, sizeof(tmp.tr)); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++){ for(int k = 0; k < n; k++) tmp.tr[i][j] += tr[i][k] * a.tr[k][j]; tmp.tr[i][j] %= mod;//這里要取模,不然可能溢出 } return tmp; }}ans, ori;matrix pow_mod(int k){ for(int i = 0; i < n; i++) ans.tr[i][i] = 1;//化為單位矩陣 while(k){ if(k&1) ans = ans*ori;//不能寫成ans *= ori,因?yàn)闆]有重載*=運(yùn)算符 k >>= 1; ori = ori*ori; }//核心代碼,下面有解釋}int main(){ int t; scanf("%d", &t); while(t--){ scanf("%d%d", &n, &k); memset(ans.tr, 0, sizeof(ans.tr)); memset(ori.tr, 0, sizeof(ori.tr)); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) scanf("%d", &ori.tr[i][j]); pow_mod(k); long long res = 0; for(int i = 0; i < n; i++){ res += ans.tr[i][i] % mod; } 核心代碼:

while(k){ if(k&1) ans = ans*ori; k >>= 1; ori = ori*ori; }

假設(shè) k = 89,其二進(jìn)制為 1011001, 顯然 a^k = ( a^1 ) * ( a^8 ) * ( a^16 ) * ( a^64 ); 也就是,k的二進(jìn)制位為0時(shí),可以跳過(右移) 。

每次判斷k的最后一位二進(jìn)制位,若為1,則 ans = ans*ori , 然后k右移一位,ori 乘以本身。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宜宾县| 手游| 鄂州市| 喀什市| 桑植县| 达拉特旗| 开鲁县| 濉溪县| 广元市| 拜泉县| 鄂伦春自治旗| 武定县| 邵阳县| 横峰县| 德安县| 财经| 静海县| 河源市| 揭西县| 酒泉市| 闵行区| 古丈县| 德保县| 韶山市| 香格里拉县| 龙井市| 莱阳市| 彭泽县| 霍州市| 班戈县| 龙陵县| 景洪市| 陆川县| 汤原县| 桐梓县| 厦门市| 云阳县| 辛集市| 宁河县| 门头沟区| 海盐县|