Time Limit: 3000MS Memory Limit: 131072K
Total Submissions: 8740 Accepted: 3739
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 4
0 1
1 1
Sample Output
1 2
2 3
代码:
#include<iostream> #include<cstdio> #include<string.h> #define N 35 using namespace std; typedef struct{ int num[N][N]; }Node; Node p,q; int n,m,k; Node add(Node a,Node b) { Node c; memset(c.num,0,sizeof(c.num)); for(int i=0;i<n;++i) for(int j=0;j<n;++j) c.num[i][j]= (a.num[i][j]+b.num[i][j])%m; return c; } Node mul(Node a,Node b) { Node c; memset(c.num,0,sizeof(c.num)); for(int i=0;i<n;++i) for(int j=0;j<n;++j) { for(int t=0;t<n;++t) c.num[i][j]= (c.num[i][j]+a.num[i][t]*b.num[t][j])%m; } return c; } Node ceil(int k) { Node a=p,b=q; while(k!=1) { if(1&k) a=mul(a,b),k--; else{k=k/2; b=mul(b,b); } } a=mul(a,b); return a; } /* 不知道这里为什么错,都是求矩阵的k次方为什么这个就不行呢,,纠结,,,不过在我的努力下我找到了。。。
今天做了两个关于矩阵的题,主要思想都是二分,,,看来二分很重要啊,,,还有就是见证了矩阵的强大,,,(*^__^*) 嘻嘻……,,
杯具的是我把2的n次方写成n>>2,杯具啊,,,,几乎杯具了一下午,,,,,
2的n次方n>>1,
代码:
#include<iostream> #include<cstdio> #include<string.h> #define N 35 using namespace std; typedef struct{ int num[N][N]; }Node; Node p,q; int n,m,k; Node add(Node a,Node b) { Node c; memset(c.num,0,sizeof(c.num)); for(int i=0;i<n;++i) for(int j=0;j<n;++j) c.num[i][j]= (a.num[i][j]+b.num[i][j])%m; return c; } Node mul(Node a,Node b) { Node c; memset(c.num,0,sizeof(c.num)); for(int i=0;i<n;++i) for(int j=0;j<n;++j) { for(int t=0;t<n;++t) c.num[i][j]= (c.num[i][j]+a.num[i][t]*b.num[t][j])%m; } return c; } Node ceil(int k) { Node a=p,b=q; while(k) { if(1&k) a=mul(a,b); b=mul(b,b); k=k>>1; } return a; } Node get_num(int k) { if(k==1) return q; Node a,b; a=get_num(k/2); if(1&k) { b=ceil(k/2+1); a=add(a,mul(a,b)); a=add(a,b); } else{ b=ceil(k/2); a=add(a,mul(b,a)); } return a; } void print_f(Node a) { for(int i=0;i<n;++i) {for(int j=0;j<n;++j) printf("%d ",a.num[i][j]%m); printf("\n"); } } int main() { while(~scanf("%d%d%d",&n,&k,&m)) { for(int i=0;i<n;++i) for(int j=0;j<n;++j) { p.num[i][j]=(i==j); scanf("%d",&q.num[i][j]); q.num[i][j]%=m; } Node ans=get_num(k); print_f(ans); } return 0; }