poj 3233 矩陣乘方

來源:互聯網
上載者:User

轉載於:http://xuyemin520.is-programmer.com/posts/26387.html

// A^n.cpp : 定義控制台應用程式的進入點。////2分法求矩陣冥次//Poj 3233#include "stdafx.h"#include <iostream>#include <algorithm>using namespace std;//如果矩陣過大或者冥過多都會造成棧溢出const int MAXN = 31;int Mod;typedef struct Matrix{int s[MAXN][MAXN];}M;int n;//a+bM Add(M a, M b){M c;for(int i=1; i<=n; i++){for(int j=1; j<=n; j++){c.s[i][j] = (a.s[i][j] + b.s[i][j]) % Mod;}}return c;}//a*bM Multiply(M a, M b){M c;memset(c.s,0,sizeof(c.s));for(int i=1; i<=n; i++){for(int j=1; j<=n; j++){for(int k=1; k<=n; k++){c.s[i][j] = (c.s[i][j] + (a.s[i][k] * b.s[k][j] % Mod))%Mod ;}}}return c;}//a^tM Pow(M a, int t){M b;if(t == 0){memset(b.s,0,sizeof(b.s));for(int i=1; i<=n; i++){b.s[i][i] = 1;}return b;}else{M k = Pow(a,t/2);if(t&1) //t為奇數{return Multiply(Multiply(k,k),a);}else{return Multiply(k,k);}}}//A + A^2 + A^3 + ... + A^tM Sum(M a, int t){M b;if(t == 1){return a;}else{M k = Sum(a,t/2);if(t&1){M p = Pow(a,t/2+1);return Add (Add(k,p) , Multiply(k,p) );}else{return Add(k , Multiply(Pow(a,t/2),k));}}}int main(){M a;int t;cin>>n>>t>>Mod;for(int i=1; i<=n; i++){for(int j=1; j<=n; j++){cin>>a.s[i][j];a.s[i][j] %= Mod;}}a = Sum(a,t);for(int i=1; i<=n; i++){for(int j=1; j<=n; j++){cout<<a.s[i][j];if(j != n)cout<<" ";}cout<<endl;}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.