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

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

二分法:

需要注意当n为偶数和奇数的时候。
Talk is cheap.just show the code!
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define LL long long
#define m(s) memset(s,0,sizeof(s))
struct mat
{
    int a[40][40];
}d;
int n,m,k,mod;

mat mul(mat a,mat b)//矩阵相乘
{
    mat ret;
    m(ret.a);
    for(int i=0;i<n;i++)
        for(int k=0;k<n;k++)
             {
                 if(a.a[i][k])
                 {
                     for(int j=0;j<n;j++)
                     {
                         ret.a[i][j]+=a.a[i][k]*b.a[k][j];
                         if(ret.a[i][j]>=mod)
                             ret.a[i][j]%=mod;
                     }
                 }
             }
    return ret;
}

mat expo(mat a,int k)//矩阵快速幂
{
    if(k==1)
        return a;
    mat e;
    m(e.a);
    for(int i=0;i<n;i++)
        e.a[i][i]=1;
    if(k==0)
        return  e;
    while(k)
    {
        if(k&1)
            e=mul(a,e);
        a=mul(a,a);
        k>>=1;
    }
    return e;
}

mat add(mat a,mat b)//矩阵相加
{
    mat t;
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            t.a[i][j]=(a.a[i][j]+b.a[i][j])%mod;
        return t;
}
mat sum(int k)//矩阵求和
{
    if(k==1)
        return d;
    if(k&1)
        return add(sum(k-1),expo(d,k));
    else
    {
        mat tmp=sum(k>>1);
        return add(tmp,mul(tmp,expo(d,k>>1)));
    }
}
int main()
{
    while(cin>>n>>k>>mod)
    {
        mat ans;
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
            {
                cin>>d.a[i][j];
                if(d.a[i][j]>=m)
                    d.a[i][j]%=mod;
            }
        ans=sum(k);
        for(int i=0;i<n;i++)
        {    
            for(int j=0;j<n;j++)
            {
                if(j)
                    cout<<" ";
                cout<<ans.a[i][j];
            }
            cout<<endl;
        }
    }
    return 0;
}

 



转载于:https://www.cnblogs.com/orion7/p/7238234.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值