zoukankan      html  css  js  c++  java
  • HDU1575-Tr 【矩阵快速幂】(模板题)

    <题目链接>

    题目大意:

    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
    ", res);
        }
        return 0;
    }


    2018-08-08
  • 相关阅读:
    cf D. Vessels
    cf C. Hamburgers
    zoj 3758 Singles' Day
    zoj 3777 Problem Arrangement
    zoj 3778 Talented Chef
    hdu 5087 Revenge of LIS II
    zoj 3785 What day is that day?
    zoj 3787 Access System
    判断给定图是否存在合法拓扑排序
    树-堆结构练习——合并果子之哈夫曼树
  • 原文地址:https://www.cnblogs.com/00isok/p/9445999.html
Copyright © 2011-2022 走看看