湘潭邀请赛 A题 矩阵快速幂

本文介绍了一种高效的算法来计算2×2矩阵的高次幂,并只保留除以7后的余数。该算法使用了快速幂运算,通过递归将指数分解以减少乘法操作的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2016

Given a 2×2 matrix

A=(a11a21a12a22),
find An where A1=A,An=A×An1. As the result may be large, you are going to find only the remainder after division by 7.

Special Note: The problem is intended to be easy. Feel free to think why the problem is called 2016 if you either:

  1. find it hard to solve;
  2. or, solved all the other problems easily.

Input

The input contains at most 40 sets. For each set:

The first line contains an integer n (1n<10100000).

The second line contains 2 integers a11,a12.

The third line contains 2 integers a21,a22.

(0aij<7(a11a22a12a21) is not a multiple of 7)

Output

For each set, a 2×2 matrix denotes the remainder of An after division by 7.

Sample Input

2
1 1
1 2
2016
1 1
1 2

Sample Output

2 3
3 5
1 0

0 1

ACcode:

#include <bits/stdc++.h>
#define maxn 100010
#define mod 7
using namespace std;
struct N{
    int mat[2][2];
}my;
inline N mul(N a,N b){
    N ret;
    for(int i=0;i<2;++i)
        for(int j=0;j<2;++j){
            ret.mat[i][j]=0;
            for(int k=0;k<2;++k)
                ret.mat[i][j]=(ret.mat[i][j]+a.mat[i][k]*b.mat[k][j]%mod)%7;
        }
    return ret;
}
inline N pow_M(N a,int n){
    N ret;
    memset(ret.mat,0,sizeof(ret.mat));
    for(int i=0;i<2;++i)ret.mat[i][i]=1;
    N tmp=a;
    while(n){
        if(n&1)ret=mul(ret,tmp);
        tmp=mul(tmp,tmp);
        n>>=1;
    }
    return ret;
}
char nn[maxn];
int main(){
    while(~scanf("%s",nn)){
        int len=strlen(nn);
        int n=0;
        for(int i=0;i<len;++i)
            n=(n*10+nn[i]-'0')%2016;
        scanf("%d%d%d%d",&my.mat[0][0],&my.mat[0][1],&my.mat[1][0],&my.mat[1][1]);
        N tmp=pow_M(my,n);
        printf("%d %d\n%d %d\n",tmp.mat[0][0]%mod,tmp.mat[0][1]%mod,tmp.mat[1][0]%mod,tmp.mat[1][1]%mod);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值