poj3233 Matrix Power Series 2011-12-21

Matrix Power SeriesTime Limit: 3000MSMemory Limit: 131072KTotal Submissions: 8896Accepted: 3814

Description

Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.

Input

The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.

Output

Output the elements of S modulo m in the same way as A is given.

Sample Input

2 2 40 11 1

Sample Output

1 22 3

Source

POJ Monthly--2007.06.03, Huang, Jinsong

 

 

_________________________________________________

已知矩阵A,求S=A+A^2+A^3+...+A^K (K<10^9)  mod m 的值。

两次二分。k为偶数时:   S=A+A^2+...+A^(K/2)+A^(K/2)*(A+A^2+...+A^(K/2));

                 k为奇数时:   S=A+A^2+...+A^(K/2)+A^(K/2+1)+A^(K/2+1)*(A+A^2+...+A^(K/2));

                      k/2等价于k div 2

_________________________________________________

  1 Program Stone;
  2 
  3 type ar=array[1..30,1..30]of longint;
  4 
  5 var i,j,k,n,m,left,right,mid:longint;
  6 
  7     a,ans,ti,qu:ar;
  8 
  9  procedure time(a,b:ar);            //矩阵相乘
 10 
 11  var i,j,k:longint;
 12 
 13   begin
 14 
 15    fillchar(ti,sizeof(ti),0);
 16 
 17     for i:=1 to n do
 18 
 19      for j:=1 to n do
 20 
 21       for k:=1 to n do
 22 
 23        ti[i,j]:=(ti[i,j]+a[i,k]*b[k,j]mod m) mod m;
 24 
 25   end;
 26 
 27  procedure quick(x:longint);           //快速幂
 28 
 29  var i,j,k:longint;
 30 
 31   begin
 32 
 33     if x=1 then begin qu:=a;exit;end;
 34 
 35     quick(x div 2);
 36 
 37     time(qu,qu);
 38 
 39     if x mod 2<>0 then time(ti,a);
 40 
 41     qu:=ti
 42 
 43   end;
 44 
 45  procedure add;         //矩阵相加
 46 
 47  var i,j,k:longint;
 48 
 49   begin
 50 
 51     for i:=1 to n do
 52 
 53      for j:=1 to n do
 54 
 55       ans[i,j]:=(ans[i,j]+ti[i,j])mod m;
 56 
 57   end;
 58 
 59  
 60 
 61  procedure divide(rc:longint);        //二分
 62 
 63  var i,j,k:longint;
 64 
 65   begin
 66 
 67     if rc=1 then begin ans:=a;exit;end;
 68 
 69     k:=rc div 2;
 70 
 71     divide(k);
 72 
 73     if rc mod 2=0 then quick(k) else quick(k+1);
 74 
 75     time(ans,qu);
 76 
 77     add;
 78 
 79     if rc mod 2<>0 then begin
 80 
 81                           ti:=qu;
 82 
 83                           add;
 84 
 85                         end;
 86 
 87   end;
 88 
 89 Begin
 90 
 91  assign(input,'input.in');reset(input);
 92 
 93  assign(output,'output.out');rewrite(output);
 94 
 95  readln(n,k,m);
 96 
 97   for i:=1 to n do
 98 
 99    for j:=1 to n do
100 
101     read(a[i,j]);
102 
103   divide(k);
104 
105   for i:=1 to n do
106 
107    begin
108 
109     for j:=1 to n do
110 
111      write(ans[i,j],' ');
112 
113     writeln;
114 
115    end;
116 
117  close(input); close(output);
118 
119 end.

 

posted on 2016-03-02 20:09  Yesphet  阅读(134)  评论(0编辑  收藏  举报