zzuli 2186 我觉得我还可以优化一下【矩阵快速幂*好题】

来源:互联网 发布:80端口被攻击 编辑:程序博客网 时间:2024/05/16 12:22

Description

现有一个n行m列的矩阵。对于矩阵中第i行第j列的元素,我们用G[i][j]来表示,已知:
1.G[1][1]=1
2.G[i][j]=a*G[i][j-1]+b (j>1)
3.G[i][1]=c*G[i-1][m]+d (i>1)
若n,m,a,b,c,d均已给出,那么G[n][m]对1,000,000,007取模的值是多少。
Input

仅一行,包含六个整数n,m,a,b,c,d。
1<=n,m,a,b,c,d<=10^9
Output

一个整数,表示G[n][m]对1,000,000,007取模的值。
Sample Input

2 2 1 2 3 4
Sample Output

15
标程思路:
这里写图片描述

#include<bits/stdc++.h>using namespace std;typedef long long LL;const LL mod = 1000000007;struct mat {    LL mapp[2][2];};mat mat_pow(mat A, mat B) {    mat C;    memset(C.mapp, 0, sizeof(C.mapp));    for(int i = 0; i < 2; i++) {        for(int j = 0; j < 2; j++) {            for(int k = 0; k < 2; k++) {                C.mapp[i][k] = (C.mapp[i][k] + A.mapp[i][j] * B.mapp[j][k]) % mod;            }        }    }    return C;}mat mat_mul(mat A, LL b) {    mat ans;    ans.mapp[0][0] = ans.mapp[1][1] = 1;    ans.mapp[0][1] = ans.mapp[1][0] = 0;    while(b) {        if(b & 1)             ans = mat_pow(ans, A);        A = mat_pow(A, A);        b >>= 1;    }    return ans;}int main() {    LL n, m, a, b, c, d;    scanf("%lld %lld %lld %lld %lld %lld", &n, &m, &a, &b, &c, &d);    mat A, B, C, D;    A.mapp[0][0] = A.mapp[0][1] = 1;    A.mapp[1][0] = A.mapp[1][1] = 0;    B.mapp[0][0] = a, B.mapp[0][1] = 0;    B.mapp[1][0] = b, B.mapp[1][1] = 1;    C.mapp[0][0] = c, C.mapp[0][1] = 0;    C.mapp[1][0] = d, C.mapp[1][1] = 1;    B = mat_mul(B, m - 1);    C = mat_pow(B, C);    C = mat_mul(C, n - 1);    C = mat_pow(A, C);    D = mat_pow(C, B);    printf("%lld\n", D.mapp[0][0] % mod);    return 0;}
原创粉丝点击