时间限制:
1000 ms | 内存限制:
65535 KB
难度:
4
-
描述
- Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
-
输入
- The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 10^9) and m (m < 10^4). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order. 输出
- Output the elements of S modulo m in the same way as A is given. 样例输入
-
2 2 4 0 1 1 1
样例输出
-
1 2 2 3
View Code1 #include<stdio.h>
2 #define Max 35
3 int matr[Max][Max];
4 int d[Max][Max];
5 int flg[Max][Max],adflg[Max][Max];
6 int pp[Max][Max];
7 int n,m;
8 void mult(int a[][Max],int b[][Max])
9 {
10 int i,j,k;
11 for(i=0;i<n;i++)
12 {
13 for(j=0;j<n;j++)
14 {
15 flg[i][j]=0;
16 for(k=0;k<n;k++)
17 flg[i][j]=(flg[i][j]+a[i][k]*b[k][j])%m;
18 }
19 }
20 }
21 void add(int a[][Max],int b[][Max])
22 {
23
24 int i,j;
25 for(i=0;i<n;i++)
26 {
27 for(j=0;j<n;j++)
28 {
29 adflg[i][j]=(a[i][j]+b[i][j])%m;
30 }
31 }
32
33 }
34 void fz(int A[][Max],int B[][Max])
35 {
36 int i,j;
37 for(i=0;i<n;i++)
38 {
39 for(j=0;j<n;j++)
40 {
41 A[i][j]=B[i][j];
42 }
43 }
44 }
45 void pows(int n)
46 {
47 int ans[Max][Max],m[Max][Max];
48 if(n==1)
49 {
50 fz(pp,matr);
51 return ;
52 }
53 else
54 {
55 pows(n/2);
56 fz(m,pp);
57 mult(m,m);
58 fz(ans,flg);
59 if(n%2==1)
60 {
61 mult(ans,matr);
62 fz(ans,flg);
63 }
64 }
65 fz(pp,ans);
66 }
67 void dp(int n)
68 {
69 int pans[Max][Max];
70 if(n==1)
71 {
72 fz(d,matr);
73 return ;
74 }
75 pows(n/2);fz(pans,pp);
76 dp(n/2);
77 mult( pans,d);
78 add(d,flg);
79 fz(d,adflg);
80 if(n%2)
81 {
82 pows(n);
83 add(d,pp);
84 fz(d,adflg);
85 }
86 }
87 int main()
88 {
89 int k,i,j;
90 scanf("%d%d%d",&n,&k,&m) ;
91
92 for(i=0;i<n;i++)
93 {
94 for(j=0;j<n;j++)
95 scanf("%d",&matr[i][j]);
96 }
97 dp(k);
98 for(i=0;i<n;i++)
99 {
100 for(j=0;j<n;j++)
101 printf("%d ",d[i][j]);
102 printf("\n");
103 }
104
105 return 0;
106 }