UVa 10870 - Recurrences

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1811

矩阵快速幂

代码:

#include<iostream>

#include<cstdio>

#include<string>

#include<cstring>

#include<cmath>

#include<set>

#include<map>

#include<stack>

#include<vector>

#include<algorithm>

#include<queue>

#include<stdexcept>

#include<bitset>

#include<cassert>

#include<deque>





using namespace std;



typedef long long ll;

typedef unsigned int uint;

const double eps=1e-12;

const int INF=0x3f3f3f3f;

const int N=50;

ll ma[N][N],mb[N][N],mc[N][N];

void matrixMul(ll a[][N],ll b[][N],int n,int m,int k,ll MOD)

{

    memset(mc,0,sizeof(mc));

    for(int i=1;i<=n;++i)

    for(int j=1;j<=k;++j)

    for(int l=1;l<=m;++l)

    mc[i][j]=(mc[i][j]+a[i][l]*b[l][j]%MOD)%MOD;

    for(int i=1;i<=n;++i)

    for(int j=1;j<=m;++j)

    a[i][j]=mc[i][j];

}

int main()

{

    //freopen("data.in","r",stdin);

    int d,n;

    ll m;

    while(cin>>d>>n>>m)

    {

        if(!d&&!n&&!m) break;

        memset(mb,0,sizeof(mb));

        for(int i=1;i<=d;++i)

        cin>>mb[i][1];

        for(int i=2;i<=d;++i)

        mb[i-1][i]=1;

        for(int i=d;i>=1;--i)

        cin>>ma[1][i];

        if(n<=d)

        {

            cout<<ma[1][d+1-n]<<endl;

            continue;

        }

        n-=d;

        while(n)

        {

            if((n&1))

            matrixMul(ma,mb,1,d,d,m);

            n=n>>1;

            matrixMul(mb,mb,d,d,d,m);

        }

        cout<<ma[1][1]<<endl;

    }

    return 0;

}

 

你可能感兴趣的:(uva)