zoukankan      html  css  js  c++  java
  • 求和(矩阵快速幂)

     

    等比数列是指从第二项起,每一项与它的前一项的比值等于同一个常数的一种数列。对于一个等比数列an=a1qn-1,它的前n项的和Sn=a1(1-qn)/(1-q)(q≠1)。现在已知A为n*n的矩阵,S=A+A2+A3+...+Am,你能否正确求出S,并且输出S中的每一个元素对1000000007取模后的值。

    输入

    输入包括n+1行,第一行包括两个正整数n, m,分别代表矩阵A的大小和S中的项数,其中1≤n≤30, 1≤m≤109。接下来n行,每行n个元素,相应地代表A中的元素x,其中0≤x≤106。

    输出

    输出包括n行,每行n个元素,相应地代表S中的每一个元素对1000000007取模后的值。

    样例输入 

    1 2019
    1
    

    样例输出 

    2019

    #include <bits/stdc++.h>
    using namespace std;
    #define int long long
    const int mod = 1e9 + 7;
    const int maxn = 126;
    int n, m;
    int a[maxn][maxn], b[maxn][maxn];
    int c[maxn][maxn];
    int i, j, k;
    
    void mul(int x[maxn][maxn], int y[maxn][maxn]) {
        for (i = 1; i <= n; i++) {
            for (j = 1; j <= n; j++) {
                c[i][j] = 0;
                for (k = 1; k <= n; k++)
                    c[i][j] = (c[i][j] + x[i][k] * y[k][j]) % mod;
            }
        }
        for (i = 1; i <= n; i++) {
            for (j = 1; j <= n; j++) {
                x[i][j] = c[i][j];
            }
        }
    }
    
    void ksm() {
        m++;
        while (m) {
            if (m & 1) mul(b, a);
            m >>= 1;
            mul(a, a);
        }
    }
    
    signed main() {
        //freopen("in","r",stdin);
        ios::sync_with_stdio(0);
        cin >> n >> m;
        for (i = 1; i <= n; i++) {
            for (j = 1; j <= n; j++) {
                cin >> a[i][j];
            }
            a[i][i + n] = a[i + n][i + n] = b[i][i] = b[i + n][i + n] = 1;
        }
        n *= 2;
    //    for (i = 1; i <= n; i++) {
    //        for (j = 1; j <= n; j++) {
    //            cout << " " << a[i][j];
    //        }
    //        cout << endl;
    //    }
        ksm();
        n /= 2;
        for (i = 1; i <= n; i++)
            b[i][i + n]--;
    
        for (i = 1; i <= n; i++) {
            for (j = 1; j <= n; j++) {
                if (j != n)
                    cout << b[i][j + n] << " ";
                else cout << b[i][j + n] << endl;
            }
        }
        return 0;
    }
    View Code

  • 相关阅读:
    HDU 5583 Kingdom of Black and White 水题
    HDU 5578 Friendship of Frog 水题
    Codeforces Round #190 (Div. 2) E. Ciel the Commander 点分治
    hdu 5594 ZYB's Prime 最大流
    hdu 5593 ZYB's Tree 树形dp
    hdu 5592 ZYB's Game 树状数组
    hdu 5591 ZYB's Game 博弈论
    HDU 5590 ZYB's Biology 水题
    cdoj 1256 昊昊爱运动 预处理/前缀和
    cdoj 1255 斓少摘苹果 贪心
  • 原文地址:https://www.cnblogs.com/xcfxcf/p/12457714.html
Copyright © 2011-2022 走看看