HDU 1575 Tr A (Fast Power matrix)

Topic links: HDU 1575

Problem Description

A is a square matrix, Tr is the trace A is represented by A (that is, on the main diagonal and all) are now required Tr (A ^ k)% 9973.

Input

The first row of data is a T, T represents a set of data there.

The first line of each data has n (2 <= n <= 10), and k (2 <= k <10 9 ^) two data. Then there are n rows, each row having n data, each data range is [0,9], representing the contents of the A matrix.

Output

Each set of data corresponding to 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

Solution

The meaning of problems

If that.

answer

Fast power matrix

Fast power matrix template title.

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 10 + 5;
const ll mod = 9973;

struct Matrix {
    int n, m;
    ll a[maxn][maxn];
    Matrix(int n = 0, int m = 0) : n(n), m(m) {}
    void input() {
        for(int i = 1; i <= n; ++i) {
            for(int j = 1; j <= n; ++j) {
                scanf("%lld", &a[i][j]);
            }
        }
    }
    void output() {
        for(int i = 1; i <= n; ++i) {
            for(int j = 1; j <= n; ++j) {
                printf("%lld", a[i][j]);
                printf("%s", j == n? "\n": " ");
            }
        }
    }
    void init() {
        memset(a, 0, sizeof(a));
    }
    void unit() {
        if(n == m) {
            init();
            for(int i = 1; i <= n; ++i) {
                a[i][i] = 1;
            }
        }
    }
    Matrix operator *(const Matrix b) {
        Matrix c(n, b.m);
        c.init();
        for(int i = 1; i <= c.n; ++i) {
            for(int k = 1; k <= m; ++k) {
                for(int j = 1; j <= c.m; ++j) {
                    c.a[i][j] = (c.a[i][j] + a[i][k] * b.a[k][j]) % mod;
                }
            }
        }
        return c;
    }
    Matrix qmod(ll b) {
        if(n == m) {
            Matrix a = *this;
            Matrix ans = Matrix(n, n);
            ans.unit();
            if(!b) return ans;
            while(b) {
                if(b & 1) ans = ans * a;
                a = a * a;
                b >>= 1;
            }
            return ans;
        }
    }
};

int main() {
    int T;
    scanf("%d", &T);
    while(T--) {
        int n;
        ll k;
        scanf("%d%lld", &n, &k);
        Matrix m(n, n);
        m.input();
        m = m.qmod(k);
        ll ans = 0;
        for(int i = 1; i <= n; ++i) {
            ans = (ans + m.a[i][i]) % mod;
        }
        printf("%lld\n", ans);
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/wulitaotao/p/11419369.html