1. 程式人生 > >[luogu P3390] 【模板】矩陣快速冪

[luogu P3390] 【模板】矩陣快速冪

題目

https://www.luogu.org/problemnew/show/P3390#sub


解題思路

這道題就是矩陣乘法的模板題,注意一下 f [ i ] [ i ]

= 1 f[i][i]=1 這個初始化就可以了。


程式碼

#include<cstdio>
#include<iostream>
#include<cstring>
#define WYC 1000000007
#define LL long long
#define rep(i,x,y) for(register long long i=x;i<=y;i++)
using namespace std; LL n,kk,f[1001][1001],a[1001][1001],c[1001][1001]; inline LL read() { LL p=0; char c=getchar(); while (!isdigit(c)) c=getchar(); while (isdigit(c)) p=(p<<3)+(p<<1)+c-48,c=getchar(); return p; } void mull() { memset(c,0,sizeof(c)); rep(i,1,n) rep(j,1,n) rep(k,1,n)
c[i][j]=c[i][j]%WYC+a[i][k]*a[k][j]%WYC; memcpy(a,c,sizeof(c)); } void mul() { memset(c,0,sizeof(c)); rep(i,1,n) rep(j,1,n) rep(k,1,n) c[i][j]=c[i][j]%WYC+f[i][k]*a[k][j]%WYC; memcpy(f,c,sizeof(c)); } int main() { n=read(),kk=read(); rep(i,1,n) rep(j,1,n) a[i][j]=read(),f[i][i]=1; for(;kk;mull(),kk>>=1) if (kk&1) mul(); rep(i,1,n) {rep(j,1,n) printf("%lld ",f[i][j]%WYC); putchar(10);} }