poj 3233 矩阵快速幂

来源:互联网 发布:淘宝上金牌卖家可信吗 编辑:程序博客网 时间:2024/05/16 07:24

Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072KTotal Submissions: 17981 Accepted: 7608

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


#include <cstdio>#include <iostream>#include <cstring>using namespace std;#define LL long long#define N 60 + 5int n, k, mod;struct Matrix{    LL m[N][N];    Matrix()    {        memset(m, 0, sizeof m);    }};Matrix Mul(Matrix a, Matrix b){    int t = 2 * n;    Matrix tmp;    for(int k = 1; k <= t; k++)        for(int i = 1; i <= t; i++)            for(int j = 1; j <= t; j++)                tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k]*b.m[k][j]) % mod;    return tmp;}Matrix mul_pow(Matrix a, int k){    Matrix res;    for(int i = 1; i <= 2 * n; i++)    res.m[i][i] = 1;    while(k)    {        if(k & 1)        res = Mul(res, a);        a = Mul(a, a);        k >>= 1;    }    return res;}int main(){    while(~scanf("%d%d%d", &n, &k, &mod))    {        Matrix M;        for(int i = 1; i <= n; i++)        {            for(int j = 1; j <= n; j++)            {                scanf("%lld", &M.m[i][j]);            }            M.m[i+n][i] = M.m[i+n][i+n] = 1;        }        M = mul_pow(M, k + 1);        for(int i = 1; i <= n; i++)        for(int j = 1; j <= n; j++)        {            LL a = M.m[i+n][j];            if(i == j) a = (a + mod - 1) % mod;            j == n ? printf("%lld\n", a) : printf("%lld ", a);        }    }    return 0;}


1 0
原创粉丝点击