POJ 3233 Matrix Power Series (矩阵快速幂+二分)


Matrix Power Series
Time Limit: 3000MS   Memory Limit: 131072K
Total Submissions: 16403   Accepted: 6980

Description

Given a n × n matrix A and a positive integerk, find the sumS =A + A2 + A3 + … +Ak.

Input

The input contains exactly one test case. The first line of input contains three positive integersn (n ≤ 30),k (k ≤ 109) andm (m < 104). Then follown lines each containingn nonnegative integers below 32,768, givingA’s elements in row-major order.

Output

Output the elements of S modulo m in the same way asA is given.

Sample Input

2 2 4
0 1
1 1

Sample Output

1 2
2 3

Source

POJ Monthly--2007.06.03, Huang, Jinsong

题目链接:http://poj.org/problem?id=3233


题目大意:就是求S = A + A2 +A3 + … +Ak

题目分析:分析可以得到
k为偶数:sum(k) = (1+A^(k/2)) *( A+A^2+……+A^(k/2)) = (1+A^(k/2)) * sum(k/2)
k为奇数:sum(k) = (1+A^((k-1)/2)) * sum(k/2) + A^k


#include 
#include 
#include 
using namespace std;
int n, m;
struct matrix
{
    int m[55][55];
}a;

matrix multiply(matrix x, matrix y)
{
    matrix ans;
    memset(ans.m, 0, sizeof(ans.m));
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            if(x.m[i][j])
                for(int k = 1; k <= n; k++)
                    ans.m[i][k] = (ans.m[i][k] + x.m[i][j] * y.m[j][k]) % m;
    return ans;
}

matrix add(matrix x, matrix y)
{
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            x.m[i][j] = (x.m[i][j] + y.m[i][j]) % m;
    return x;
}

matrix quickmod(matrix a, int p)
{
    matrix ans;
    memset(ans.m, 0, sizeof(ans.m));
    for(int i = 1; i <= n; i++)
        ans.m[i][i] = 1;
    while(p)
    {
        if(p & 1)
            ans = multiply(ans, a);
        p >>= 1;
        a = multiply(a, a);
    }
    return ans;
}

matrix solve(matrix a, int k)
{
    if(k == 1)
        return a;
    matrix ans;
    memset(ans.m, 0, sizeof(ans.m));
    for(int i = 1; i <= n; i++)
        ans.m[i][i] = 1;
    ans = add(ans, quickmod(a, k >> 1));
    ans = multiply(ans, solve(a, k >> 1));
    if(k & 1) //奇数
        ans = add(ans, quickmod(a, k));
    return ans;
}

int main()
{
    int k;
    scanf("%d %d %d", &n, &k, &m);
    matrix ans, a;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            scanf("%d", &a.m[i][j]);
    ans = solve(a, k);
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j < n; j++)
            printf("%d ", ans.m[i][j]);
        printf("%d\n",ans.m[i][n]);
    }
}




你可能感兴趣的:(数论,二分/三分/两点法,POJ,矩阵快速幂,二分)