码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1575-Tr 【矩阵快速幂】(模板题)

时间:2018-08-08 22:31:00      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:while   ace   content   print   tput   mes   turn   ring   size   

<题目链接>

 

A为一个方阵,则Tr A表示A的迹(就是主对角线上各项的和),现要求Tr(A^k)%9973。 

Input

数据的第一行是一个T,表示有T组数据。 
每组数据的第一行有n(2 <= n <= 10)和k(2 <= k < 10^9)两个数据。接下来有n行,每行有n个数据,每个数据的范围是[0,9],表示方阵A的内容。 
Output

对应每组数据,输出Tr(A^k)%9973。

Sample Input

2
2 2
1 0
0 1
3 99999999
1 2 3
4 5 6
7 8 9

Sample Output

2
2686

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;
const int mod = 9973;

struct Matrix
{
    int arr[20][20];
}init,tmp;

int n;

Matrix Mul(Matrix a, Matrix b)         //矩阵相乘
{
    Matrix temp;
    for(int i=0;i<n;i++)
        for (int j = 0; j < n; j++)
        {
            temp.arr[i][j] = 0;
            for (int k = 0; k < n; k++)
            {
                temp.arr[i][j] = (temp.arr[i][j] + a.arr[i][k] * b.arr[k][j] % mod) % mod;
            }
        }
    return temp;
}

Matrix Pow(Matrix ans, Matrix a, int x)     //快速幂
{
    while (x)
    {
        if (x & 1)
        {
            ans = Mul(ans, a);
        }
        x >>= 1;
        a = Mul(a, a);
    }
    return ans;
}


int main()
{
    int t; scanf("%d", &t);
    while (t--)
    {
        int k;
        scanf("%d%d", &n, &k);
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
            {
                scanf("%d", &init.arr[i][j]);
                tmp.arr[i][j] = init.arr[i][j];
            }
        Matrix ans=Pow(init, tmp, k - 1);

        int res = 0;
        for (int i = 0; i < n; i++)
        {
            res = (res + ans.arr[i][i]) % mod;
        }
        printf("%d\n", res);
    }
    return 0;
}


2018-08-08

HDU1575-Tr 【矩阵快速幂】(模板题)

标签:while   ace   content   print   tput   mes   turn   ring   size   

原文地址:https://www.cnblogs.com/00isok/p/9445999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!