hdu 1575(矩阵乘法)

#include<stdio.h>
#include<string.h>
const int mod = 9973;
#define maxn 15
struct matrix
{
    int arr[maxn][maxn];
};

matrix mul(struct matrix a,struct matrix b,int n)
{
    int i,j,k,temp;
    struct matrix val;
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
        {
            for(k=1,temp=0;k<=n;k++)
                temp+=a.arr[i][k]*b.arr[k][j];
            val.arr[i][j]=temp%mod;
        }
    return val;
}
int  dichotomy(int n,int times,struct matrix init)
{
    struct matrix unit;
    int i;
    memset(unit.arr,0,sizeof(unit.arr));
    for(i=1;i<=n;i++)
        unit.arr[i][i]=1;
    while(times>0)
    {
        if(times&1)
        {
            unit=mul(unit,init,n);
        }
        init=mul(init,init,n);
        times>>=1;
    }
    int ans=0;
    for(i=1;i<=n;i++)
        ans+=unit.arr[i][i];
    return ans%mod;
}
int main()
{
    int t,n,k;
    int i,j,ans;
    struct matrix init;
   // freopen("input.txt","r",stdin);
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&k);
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
                scanf("%d",&init.arr[i][j]);
        }
        ans=dichotomy(n,k,init);
        printf("%d\n",ans);
    }
    return 0;
}

 

 

posted @ 2012-11-21 17:16  M_cag  阅读(168)  评论(0编辑  收藏  举报