POJ3233(递推+矩阵快速幂)

矩阵十题3
递推求矩阵前n次幂的和,想明白了还是不难,还是要多做题啊
long long 会超时,int 不会,特地百度了一下,发现原来long long 的运算比int慢
code:

#include
#include
#include
#include
#include
#include
#include 
#include
//a&3==a%4
using namespace std ;
#define ll int
#define mem(a) memset(a,0,sizeof(a))
const double eps = 1e-8;
const int maxn = 110010;
const int inf = 0x3f3f3f3f;
ll mod;

struct matrix
{
    ll mat[30][30];
    matrix()
    {
        memset(mat,0,sizeof(mat));
    }
};

void out(matrix res,int n)
{
    for(int i=0;icout<0];
        for(int j=1;jcout<<" "<cout<int n)
{
    matrix res;
    for(int i=0;ifor(int j=0;jreturn res;
}

matrix multiply(matrix a,matrix b,int n)
{
    matrix res;
    for(int i=0;ifor(int j=0;jfor(int k=0;kreturn res;
}

matrix quickmi(matrix a,ll b,int n)
{
    matrix E;
    matrix res;
    for(int i=0;i1;
        res.mat[i][i]=1;
    }
    E=multiply(a,E,n);
    while(b>0)
    {
        if(b%2==1)
        {
            res=multiply(res,E,n);
        }
        b=b/2;
        E=multiply(E,E,n);
    }
    return res;
}

matrix s(matrix sum,ll k,int n)
{
    matrix res;
    matrix tmp1;
    matrix tmp2;
    if(k<=1)
    {
        return sum;
    }
    else
    {
        if(k%2==1)
        {
            tmp1=s(sum,k-1,n);
            tmp2=quickmi(sum,k,n);
            return add(tmp1,tmp2,n);
        }
        else
        {
            tmp1=s(sum,k/2,n);
            tmp2=quickmi(sum,k/2,n);
            tmp2=multiply(tmp2,tmp1,n);
            return add(tmp1,tmp2,n);
        }
    }
    return res;
}

int main()
{
    int n;
    ll k,m;
    while(cin>>n>>k>>m)
    {
        mod=m;
        //cout<
        matrix sum;
        for(int i=0;ifor(int j=0;jcin>>sum.mat[i][j];
            }
        }
        matrix res=s(sum,k,n);
        out(res,n);
    }
    return 0;
}

你可能感兴趣的:(poj,数学,矩阵快速幂)