UVA - 11149 Power of Matrix

矩阵快速幂 - 倍增法

以及二分求和

(以上说法纯属个人理解方式)

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<map>

using namespace std;
const int maxn = 40 + 7;
int n;

struct M {
    int m[maxn][maxn];
    void init() {
        memset(m, 0, sizeof m);
    }
    M() {}
    //~M() {}
    M(char e) {
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < n; ++j)
            m[i][j] = (i == j ? 1 : 0);
    }
};
M a, ans;

M mod(M s) {
    for(int i = 0; i < n; ++i)
        for(int j = 0 ; j < n; ++j)
        s.m[i][j] %= 10;
    return s;
}

M sum(M a1, M a2) {
    M c; c.init();
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < n; ++j) {
            c.m[i][j] = (a1.m[i][j] + a2.m[i][j]) % 10;
        }
    }
    return c;
}

M mul(M a1, M a2) {
    M c; c.init();
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < n; ++j) {
            for(int k = 0; k < n; ++k) {
                c.m[i][j] = ( c.m[i][j] + (a1.m[i][k] * a2.m[k][j]))%10;
            }
            //c.m[i][j] %= 10;
        }
    }
    return c;
}

M mi(int s) {
    M E('e'), t; //t.init();
    t = a;
    while(s) {
        if(s & 1) E = mul(E, t);
        t = mul(t, t);
        //mod(E), mod(t);
        s /= 2;
    }//cout << " 2333 " << endl;
    mod(E);
    return E;
}

M solve(int k) {
    M ret; //ret.init();
    M E('e');
    if(k == 0) return E;
    if(k == 1) return a;
    ret = mul(sum(E, mi(k/2)), solve(k/2));
    if(k & 1) ret = sum(ret, mi(k));
    mod(ret);
    return ret;
}

void print(M s) {
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < n; ++j) {
            if(j) cout << " ";
            cout << s.m[i][j]%10;
        }
        cout << endl;
    }
    cout << endl;
}

int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    int k;
    while(scanf("%d%d", &n, &k) && n ) {
        a.init();//, ans.init();
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < n; ++j) {
                 cin >> a.m[i][j];
                 a.m[i][j] %= 10;
            }

        ans = solve(k);
        mod(ans);
        print(ans);
    }
    return 0;
}

/*
5 512
0 0 0 2 0
0 2 2 2 2
0 0 2 2 0
1 1 1 1 1
1 1 1 1 1
*/


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值