比赛 矩阵乘法练习赛 评测结果 RRRRRRRRRR
题目名称 矩阵幂之和 最终得分 0
用户昵称 ChenBp 运行时间 0.029 s
代码语言 C++ 内存使用 3.37 MiB
提交时间 2025-04-28 21:32:28
显示代码纯文本
#include <iostream>
#include <vector> 
#include <cstdio>
#define ll long long
using namespace std;
long long  n,k,mod=1e18;
template<typename T>
struct Matrix {
	vector<vector<T>>mat;
	ll n,m,MOD;
    Matrix(int n,int m,T mod):n(n),m(m),MOD(mod) {
        mat.resize(n,vector<T>(m,0));
    }
    void set(int i, int j, T value) {
        mat[i][j]=value%MOD;
    }
    T get(int i, int j) const {
        return mat[i][j];
    }
    void print() const {
        for (int i=0;i<n;i++) {
            for (int j=0;j<m;j++) {
                cout<<mat[i][j]<< " ";
            }
            cout << endl;
        }
    }
	Matrix<T>operator+(const Matrix<T>b)const{
	    Matrix<T> ans(n,m,MOD);
        if(n!=b.n||m!=b.m) return ans;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                ans.set(i,j,(get(i,j)+b.get(i,j))&MOD);
            }
        }
        return ans;
    }
    Matrix<T>operator-(const Matrix<T>b)const{
        Matrix<T> ans(n,m,MOD);
        if(n!=b.n||m!=b.m) return ans;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                ans.set(i,j,(get(i,j)-b.get(i,j))&MOD);
            }
        }
        return ans;
    }
	Matrix<T>operator*(const Matrix<T>b)const{
	    Matrix<T> ans(n,m,MOD);
        if(m!=b.n) return ans;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                ans.set(i,j,0);
                for(int k=1;k<=m;k++){
                    ans.set(i,j,(get(i,j)*b.get(i,j))&MOD);
                }
            }
        }
        return ans;
    }
     Matrix<T> pow(ll exp) const {
        Matrix<T> result(n,n,MOD);
        for (int i = 0; i < n; ++i) {
            result.mat[i][i] = 1;
        }
        Matrix<T> base = *this;

        while (exp > 0) {
            if (exp % 2 == 1) {
                result = result * base;
            }
            base = base * base;
            exp /= 2;
        }
        return result;
    }
};

int main(){
    freopen("gcdsum.in","r",stdin);
    freopen("gcdsum.out","w",stdout);
    cin>>n>>k>>mod;
    Matrix<ll>a(n,n,mod);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            int v;
            cin>>v;
            a.set(i,j,v);
        }
    }
    Matrix<ll>s(n,n,mod);
    for(int i=1;i<=k;i++){
        s=s+a.pow(i);
    }
    s.print();
    return 0;
}