HDU ~ 1575 ~ Tr A (矩阵快速幂)

思路:模板题,模板题。


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 9973;
struct mat
{
    int r, c;
    ll m[15][15];        

    mat (int r, int c)
    {
        this->r = r, this->c = c;
        memset(m, 0, sizeof(m));
    }

    mat operator + (mat a) const
    {
        mat ans(r, c);
        for (int i = 1; i <= r; i++)
        {
            for (int j = 1; j <= c; j++)
            {
                ans.m[i][j] = (m[i][j] + a.m[i][j]) % MOD;
            }
        }
        return ans;
    }

    mat operator * (mat a) const
    {
        mat tmp(r, a.c);
        for (int i = 1; i <= tmp.r; i++)
        {
            for (int j = 1; j <= tmp.c; j++)
            {
                tmp.m[i][j] = 0;
                for (int k = 1; k <= c; k++)
                {
                    tmp.m[i][j] = (tmp.m[i][j] + (m[i][k] * a.m[k][j]) % MOD) % MOD;
                }
            }
        }
        return tmp;
    }

    mat operator ^ (int n) const //注意运算符优先级比较低,多用括号;
    {
        mat ans(r, r), tmp(r, r);
        memcpy(tmp.m, m, sizeof(tmp.m));
        for (int i = 1; i <= ans.r; i++) ans.m[i][i] = 1;
        while(n)
        {
            if(n&1) ans = ans*tmp;
            tmp = tmp*tmp;
            n >>= 1;
        }
        return ans;
    }

    void print() const
    {
        for (int i = 1; i <= r; i++)
        {
            for (int j = 1; j <= c; j++)
            {
                printf("%lld",m[i][j]);
                if (j == c) printf("\n");
                else printf(" ");
            }
        }
    }

};
int main()
{
    int T; scanf("%d", &T);
    while (T--)
    {
        int n, k;
        scanf("%d%d", &n, &k);
        mat A(n, n);
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                scanf("%d", &A.m[i][j]);
            }
        }
        A = (A^k);
        int ans = 0;
        for (int i = 1; i <= n; i++) ans = (ans + A.m[i][i])%MOD;
        cout << ans << endl;
    }
    return 0;
}
/*
2
2 2
1 0
0 1
3 99999999
1 2 3
4 5 6
7 8 9
*/


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZscDst/article/details/79952208
个人分类: 【dp+优化】
上一篇51Nod ~ 1770 ~ 数数字 (模拟 + 找循环节)
下一篇POJ ~ 3070 ~ Fibonacci (矩阵快速幂模板)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭