HDU-1575 tr

Source: Internet
Author: User

Description

If a is a square matrix, tr a indicates the trace of A (the sum of all items on the primary diagonal). tr (a ^ K) % 9973 is required.

Input

The first row of data is a T, indicating that there is a T group of data.
The first row of each data group contains N (2 <= n <= 10) and K (2 <= k <10 ^ 9) data. Next there are n rows, each row has n data, and the range of each data is [], which indicates the content of square matrix.

Output

Output tr (a ^ K) % 9973 for each group of data.

Sample Input

 22 21 00 13 999999991 2 34 5 67 8 9 

Sample output

 22686 

Idea: Just a matrix multiplication quick power

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MOD = 9973;struct Matrix {int arr[12][12];}init, unit;int n,k;Matrix Mul(Matrix a, Matrix b) {Matrix c;for (int i = 0; i < n; i++)for (int j = 0; j < n; j++) {c.arr[i][j] = 0;for (int k = 0; k < n; k++)c.arr[i][j] = (c.arr[i][j]+(a.arr[i][k]*b.arr[k][j])%MOD)%MOD;}return c;}Matrix Pow(Matrix a, Matrix b, int x) {while (x) {if (x & 1)b = Mul(b, a);x >>= 1;a = Mul(a, a);}return b;}int main() {int t;scanf("%d", &t);while (t--) {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]);unit.arr[i][j] = init.arr[i][j];}Matrix res = Pow(init, unit, k-1);int ans = 0;for (int i = 0; i < n; i++) ans = (ans + res.arr[i][i]) % MOD;printf("%d\n", ans%MOD);}return 0;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.