矩阵快速幂 HDU1575

题目连接

真·模版水题,套模版即过

#include "bits/stdc++.h"
using namespace std;

typedef long long LL;
#define mod 9973

struct MATRIX
{
    LL m[15][15];
};

MATRIX IN;
MATRIX E;
LL n,k;

MATRIX mul(MATRIX a, MATRIX b)      //矩阵乘法
{
    MATRIX ans;
    memset(ans.m, 0, sizeof ans.m); 
    for(int i=0; i<n; i++)      //第i行结果 
    {
        for(int j=0; j<n; j++)  //第j列结果 
        {
            for(int k=0; k<n; k++)
            {
                ans.m[i][j] = (ans.m[i][j] + a.m[i][k] * b.m[k][j]) % mod;
            }
        }
    }
    return ans;
}

MATRIX quickpow(LL q)       //快速幂
{
    MATRIX ans = E;
    MATRIX M = IN;
    while(q > 0)
    {
        if(q & 1)   //判断奇偶
            ans = mul(ans, M);
        M = mul(M, M);
        q >>= 1;
    }
    return ans;
}

int main()
{
    memset(E.m, 0, sizeof E.m);
    int p;
    for(p = 0; p < 10; p++)
        E.m[p][p] = 1;
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%lld%lld", &n, &k);
        int i;
        memset(IN.m, 0, sizeof IN.m);
        for(i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++)
            {
                scanf("%d", &IN.m[i][j]);
            }
        }
        MATRIX ans = quickpow(k);
        LL pri = 0;
        for(i = 0; i < n; i++)
        {
            pri = (pri + ans.m[i][i]) % mod; 
        }
        printf("%lld\n", pri);
    }
    return 0;
}

你可能感兴趣的:(矩阵快速幂 HDU1575)