CodeForces 893B Beautiful Divisors

来源:互联网 发布:软件企业认证 年限 编辑:程序博客网 时间:2024/05/17 03:02

C - Matrix Power Series
Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.

Input
The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.

Output
Output the elements of S modulo m in the same way as A is given.

Sample Input
2 2 4
0 1
1 1

Sample Output
1 2
2 3`

#include<iostream>#include<vector>//#include<algorithm>using namespace std;typedef vector<int>vec;typedef vector<vec>mat;typedef long long ll;int M;  int n, K;//计算A*Bmat mul(mat&A, mat&B) {    mat C(A.size(), vec(B[0].size()));    for (int i = 0; i < A.size(); i++) {        for (int k = 0; k < B.size(); k++) {            for (int j = 0; j < B[0].size(); j++) {                C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % M;            }        }    }    return C;}mat pow(mat A,ll n) {    mat B(A.size(), vec(A.size()));    for (int i = 0; i < A.size(); i++) {        B[i][i] = 1;    }    while (n > 0) {        if (n & 1)B = mul(B, A);        A = mul(A, A);        n >>= 1;    }    return B;}mat add(mat a,mat b) {    mat c(a.size(), vec(b.size()));    for (int i = 0; i < n; i++)        for (int j = 0; j < n; j++)            c[i][j] = (a[i][j] + b[i][j])%M;    return c;}int main() {    int val;    cin >> n >> K >> M;    mat A(n),B(n),tmp(n);    for (int i = 0; i < n; i++){        for (int j = 0; j < n; j++) {            cin >> val;            A[i].push_back(val);            B[i].push_back(0);        }    }    for (int i = 1; i <= K; i++)    {        tmp = pow(A, i);        B = add(tmp, B);    }    for (int i = 0; i < n; i++) {        for (int j = 0; j < n; j++) {            cout << B[i][j]<<" ";        }        cout << endl;    }    system("pause");    return 0;}