51Nod - 1113 矩阵快速幂
51Nod - 1113 矩阵快速幂
给出一个N * N的矩阵,其中的元素均为正整数。求这个矩阵的M次方。由于M次方的计算结果太大,只需要输出每个元素Mod (10^9 + 7)的结果。
Input
第1行:2个数N和M,中间用空格分隔。N为矩阵的大小,M为M次方。(2 <= N <= 100, 1 <= M <= 10^9) 第2 - N + 1行:每行N个数,对应N * N矩阵中的1行。(0 <= N[i] <= 10^9)
Output
共N行,每行N个数,对应M次方Mod (10^9 + 7)的结果。
Input示例
2 3 1 1 1 1
Output示例
4 4 4 4
题解:
快速矩阵幂。
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
const int MOD = 1e9 + 7;
typedef long long LL;
int n, m, x;
vector<vector<LL> > multiple(const vector<vector<LL> > &a, const vector<vector<LL> > &b){
vector<vector<LL> > ans(n, vector<LL>(n, 0));
for(int i=0; i<n; ++i){
for(int j=0; j<n; ++j){
for(int k=0; k<n; ++k){
ans[i][j] += (a[i][k] * b[k][j]) % MOD;
ans[i][j] = ans[i][j] % MOD;
}
}
}
return ans;
}
vector<vector<LL> > power_matrix(vector<vector<LL>> t, int num){
vector<vector<LL> > ans(n, vector<LL>(n, 0));
for(int i=0; i<n; ++i){
ans[i][i] = 1;
}
while(num){
if(num%2 == 1){
ans = multiple(ans, t);
}
t = multiple(t, t);
num = num / 2;
}
return ans;
}
int main(){
while(scanf("%d %d", &n, &m) != EOF){
vector<vector<LL> > t;
for(int i=0; i<n; ++i){
vector<LL> tmp;
for(int j=0; j<n; ++j){
scanf("%d", &x);
tmp.push_back(x);
}
t.push_back(tmp);
}
vector<vector<LL> > ans = power_matrix(t, m);
for(int i=0; i<n; ++i){
for(int j=0; j<n-1; ++j){
printf("%d ", ans[i][j] );
}
printf("%d\n", ans[i][n-1] );
}
}
return 0;
}

浙公网安备 33010602011771号