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

大家都很强,可与之共勉

额,第一次写的暴力,果断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]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值