您的位置:首页 > 其它

T解 POJ-3233 [矩阵快速幂][矩阵乘法][二分求解]

2017-03-18 20:12 405 查看

大家都很强,可与之共勉

额,第一次写的暴力,果断TLE。然后第二次用二分法,时间过于长。YYF告诉我可以减少初始化次数与mod的次数,虽然我不知道怎么减少mod次数。

PS::重定义运算符,比函数慢一些。

Matrix Power Series

Time Limit: 3000MS Memory Limit: 131072K

Total Submissions: 11954 Accepted: 5105

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 "cctype"
#include "cstdio"
#include "cstring"

template <class T>
inline bool readIn(T &x)  {
x = 0;
T flag = 1;
char ch = (char)getchar();
while (!isdigit(ch))  {
if (ch == '-')  flag = -1;
ch = (char)getchar();
}

while (isdigit(ch))
x = (x << 1) + (x << 3) + ch -  48,
ch = (char)getchar();
x *= flag;
}

template <class T>
inline void write(T x)  {
if (x > 9)
write(x / 10);
putchar(x % 10 + 48);
}

template <class T>
inline bool writeIn(T x)  {
if( x < 0 )  {
putchar('-');
x = -x;
}
write(x);
putchar(' ');
}

int n, k, m;

struct Matrix  {
int m[30][30];
inline bool unit()  {
memset(m, 0, sizeof(m));
for (int i = 0; i < n; m[i][i] = 1, ++i);
}
inline bool empty()  {
memset(m, 0, sizeof(m));
}
} a;

Matrix operator * ( Matrix a, Matrix b )  {
Matrix c;   c.empty();
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
for(int k = 0; k < n; ++k)
c.m[i][j] = (c.m[i][j] + a.m[i][k] * b.m[k][j]) % m;
return c;
}

Matrix operator + ( Matrix a, Matrix b )  {
Matrix c;
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
c.m[i][j] = (a.m[i][j] + b.m[i][j]) % m;
return c;
}

inline Matrix pow( Matrix a, int x )  {
Matrix rt;
for (rt.unit(); x; (x & 1) ? rt = rt * a : rt, x >>= 1, a = a * a);
return rt;
}

Matrix sum ( Matrix s , int k )  {
if ( k == 1 )  return s ;
Matrix tmp ;   tmp.unit();
tmp = tmp + pow( s , k >> 1 );
tmp = tmp * sum( s , k >> 1 );
if ( k & 1 )
tmp = tmp + pow( s , k );
return tmp ;
}

int main()  {
readIn(n), readIn(k), readIn(m);
for(int i = 0; i < n; ++i)  for(int j = 0; j < n; ++j)  readIn(a.m[i][j]);
a = sum(a, k);
for(int i = 0; i < n; printf("\n"), ++i)  for(int j = 0; j < n; ++j)  writeIn(a.m[i][j]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: