Reading comprehension HDU - 4990(矩阵快速幂 递推)

 Read the program below carefully then answer the question.
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>

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=(ans*2+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

题意:当n为奇数时,f[n] = 2*f[n-1]+1,f[n-1] = 2*f[n-2],所以:f[n] = f[n-1] + 2*f[n-2] + 1;
当n为偶数时,f[n] = 2*f[n-1],f[n-1] = 2*f[n-2] + 1,所以:f[n] = f[n-1] + 2*f[n-2] + 1;
综上:f[n] = f[n-1] + 2*f[n-2] + 1,构造矩阵:
这里写图片描述
利用矩阵快速幂求f(n)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
typedef long long LL;
LL MOD;
const int Size = 3;
struct MA
{
    LL mat[Size][Size];
};

MA mul(MA x, MA y)
{
    MA ret;
    memset(ret.mat, 0, sizeof(ret.mat));
    for(int i = 0; i<Size; i++)
    for(int j = 0; j<Size; j++)
    for(int k = 0; k<Size; k++)
    {
        ret.mat[i][j] += (1LL*x.mat[i][k]*y.mat[k][j])%MOD;
        ret.mat[i][j] %= MOD;
    }
    return ret;
}

MA qpow(MA x, LL y)
{
    MA s;
    memset(s.mat,0,sizeof(s.mat));
    for(int i=0;i<Size;i++) s.mat[i][i] = 1;
    while(y)
    {
        if(y&1) s = mul(s, x);
        x = mul(x, x);
        y >>= 1;
    }
    return s;
}

MA tmp = {
    1, 2, 1,
    1, 0, 0,
    0, 0, 1
};

int main()
{
    LL n, m;
    while(~scanf("%lld%lld",&n,&m))
    {
        MOD = m;
        if(n<=2)
        {
            printf("%lld\n", n%MOD);
            continue;
        }

        MA s = tmp;
        s = qpow(s, n-2);
        LL ans = ((2LL*s.mat[0][0]%MOD + s.mat[0][1])%MOD+s.mat[0][2])%MOD;
        printf("%lld\n", ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值