首页 > 其他 > 详细

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

时间:2015-02-18 21:01:11      阅读:364      评论:0      收藏:0      [点我收藏+]


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

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

Source

POJ Monthly--2007.06.03, Huang, Jinsong

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


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

题目分析:分析可以得到sum(k) = (1+A^(k/2)) *( A+A^2+……+A^(k/2)) = (1+A^(k/2)) * sum(k/2),如果k为奇数的话需要加上A^(k/2 + 1)


#include <cstdio>
#include <cstring>
#include <algorithm>
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 3233 Matrix Power Series (矩阵快速幂+二分)

原文:http://blog.csdn.net/tc_to_top/article/details/43878231

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!