Matrix Power Series POJ 3233

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
 
using namespace std;
int mod;
int n;
struct node{
    int ma[40][40];
}init, res;

node Mult(node x,node y)
{
    int i, j, k;
    node tmp;
    memset(tmp.ma,0,sizeof(tmp.ma));
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            for(k=0;k<n;k++)
                tmp.ma[i][j]=(tmp.ma[i][j]+x.ma[i][k]*y.ma[k][j])%mod;
    return tmp;
}

node Pow(node x, int k)
{
    node tmp;
    int i, j;
    memset(tmp.ma,0,sizeof(tmp.ma));
    for(i=0;i<n;i++)
		tmp.ma[i][i]=1;
    while(k)
    {
        if(k&1) tmp=Mult(tmp,x);
        x=Mult(x,x);
        k>>=1;
    }
    return tmp;
}
node add(node x,node y)
{
    int i, j;
    node tmp;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            tmp.ma[i][j]=(x.ma[i][j]+y.ma[i][j])%mod;
        }
    }
    return tmp;
}
node sum(node x, int k)
{
    node tmp, y;
    if(k==1) return x;
    tmp=sum(x,k/2);
    if(k&1)
    {
        y=Pow(x,k/2+1);
        tmp=add(Mult(y,tmp),tmp);
        return add(tmp,y);
    }
    else
    {
        y=Pow(x,k/2);
        return add(Mult(y,tmp),tmp);
    }
}
int main()
{
    int k, m, x, i, j;
    scanf("%d%d%d",&n,&k,&mod);
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            scanf("%d",&x);
            init.ma[i][j]=x%mod;
        }
    }
    res=sum(init, k);
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("%d",res.ma[i][j]);
            if(j!=n-1) printf(" ");
        }
        printf("\n");
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章