51nod 矩陣快速冪模版題
阿新 • • 發佈:2019-02-04
給出一個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 <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <set>
#include <algorithm>
typedef long long ll;
using namespace std;
const int N=100+1;
const ll mod=1e9+7;
int n;
struct node
{
ll cnt[N][N];
void CSH()
{
memset(cnt,0,sizeof(cnt));
}
void init()
{
CSH();
for(int i=0;i<n;i++)
cnt[i][i]=1;
}
};
node mul(node x,node y)
{
node b;
b.CSH();
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(x.cnt[i][j])
for(int k=0;k<n;k++)
b.cnt[i][k]=(x.cnt[i][j]*y.cnt[j][k]+b.cnt[i][k])%mod;
return b;
}
node quick(node x,ll m)
{
node sum;
sum.init();
while(m)
{
if(m%2) sum=mul(sum,x);
x=mul(x,x);
m/=2;
}
return sum;
}
int main()
{
ll m;
node a;
scanf("%d%lld",&n,&m);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%lld",&a.cnt[i][j]);
node k=quick(a,m);
for(int i=0;i<n;i++)
{
printf("%lld",k.cnt[i][0]);
for(int j=1;j<n;j++)
printf(" %lld",k.cnt[i][j]);
puts("");
}
}