洛谷P3390
题目背景
矩阵快速幂
题目描述
给定n*n的矩阵A,求A^k
输入输出格式
输入格式:
第一行,n,k
第2至n+1行,每行n个数,第i+1行第j个数表示矩阵第i行第j列的元素
输出格式:
输出A^k
共n行,每行n个数,第i行第j个数表示矩阵第i行第j列的元素,每个元素模10^9+7
输入输出样例
输入样例#1:
2 1
1 1
1 1
输出样例#1:
1 1
1 1
说明
n<=100, k<=10^12, |矩阵元素|<=1000
算法:矩阵快速幂
矩阵快速幂模板:
1 program rrr(input,output); 2 const 3 cs=1000000007; 4 var 5 a,c,ans:array[0..110,0..110]of int64; 6 n,i,j,k:longint; 7 m:int64; 8 begin 9 assign(input,'r.in');assign(output,'r.out');reset(input);rewrite(output); 10 readln(n,m); 11 for i:=1 to n do for j:=1 to n do read(a[i,j]); 12 fillchar(ans,sizeof(ans),0); 13 for i:=1 to n do ans[i,i]:=1; 14 while m>0 do 15 begin 16 if m mod 2=1 then 17 begin 18 //c:=ans*a; 19 for i:=1 to n do for j:=1 to n do begin c[i,j]:=0;for k:=1 to n do c[i,j]:=(c[i,j]+ans[i,k]*a[k,j]) mod cs; end; 20 //ans:=c; 21 for i:=1 to n do for j:=1 to n do ans[i,j]:=c[i,j]; 22 end; 23 //c:=a*a; 24 for i:=1 to n do for j:=1 to n do begin c[i,j]:=0;for k:=1 to n do c[i,j]:=(c[i,j]+a[i,k]*a[k,j]) mod cs; end; 25 //a:=c; 26 for i:=1 to n do for j:=1 to n do a[i,j]:=c[i,j]; 27 m:=m>>1; 28 end; 29 for i:=1 to n do begin for j:=1 to n do write(ans[i,j],' ');writeln; end; 30 close(input);close(output); 31 end.