Reading comprehension

Reading comprehension

Read the program below carefully then answer the question.
#pragma comment(linker, “/STACK:1024000000,1024000000”)
#include
#include
#include
#include
#include
#include

const int MAX=100000*2;
const int INF=1e9;

int main()
{
int n,m,ans,i;
while(scanf("%d%d",&n,&m)!=EOF)
{
ans=0;
for(i=1;i<=n;i++)
{
if(i&1)ans=(ans2+1)%m;
else ans=ans
2%m;
}
printf("%d\n",ans);
}
return 0;
}
Input
Multi test cases,each line will contain two integers n and m. Process to end of file.
[Technical Specification]
1<=n, m <= 1000000000
Output
For each case,output an integer,represents the output of above program.
Sample Input
1 10
3 100
Sample Output
1
5

大致题意:阅读这段程序,求f(n)%m的值
思路:n,m均很大,因此想到了矩阵快速幂(方法貌似不唯一,我构造了一个2*2的初始矩阵,第一行第一列表示第一个值,第二行第一列表示第二个值)

在这里插入图片描述

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;

struct matrix
{
    ll x[105][105];
    ll n, m;
    matrix(){memset(x, 0, sizeof(x));}
};

ll n, m;

matrix multiply(matrix &a, matrix &b)
{
    matrix c;
    c.n = a.n, c.m = b.m;
    for(int i = 1; i <= a.n; i++){
        for(int j = 1; j <= a.m; j++){
            for(int k = 1; k <= a.m; k++){
                c.x[i][j] += a.x[i][k]*b.x[k][j];
            }
            c.x[i][j] %= m;
        }
    }
    return c;
}

matrix mpow(matrix &a, ll m)
{
    matrix change;
    change.n = 2;
    change.m = 2;
    change.x[1][1] = 4;
    change.x[1][2] = 0;
    change.x[2][1] = 1;
    change.x[2][2] = 1;

    while(m > 0){
        if(m & 1)a = multiply(a, change);
        change = multiply(change, change);
        m >>= 1;
    }
    return a;
}

int main()
{
    while(~scanf("%lld%lld", &n, &m)){
        matrix a;
        a.n = a.m = 2;
        a.x[1][1] = 1;
        a.x[1][2] = 1;
        a.x[2][1] = 2;
        a.x[2][2] = 2;
        if(n == 1){
            printf("%lld\n", n % m);
            continue;
        }
        else if(n == 2){
            printf("%lld\n", 2 % m);
            continue;
        }

        matrix res;
        res =  mpow(a, (n - 1)/2);
        if(n & 1){
            printf("%lld\n", res.x[1][1] % m);
        }else{
            printf("%lld\n", res.x[2][1] % m);
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值