Reading comprehension HDU - 4990(打表找递推式+矩阵快速幂)

本文介绍了一种使用矩阵快速幂技术优化动态规划问题的解决方法,具体针对一种特殊的递推公式进行优化,通过构建特定的关系矩阵并利用快速幂算法,实现了对大规模数据的有效处理。

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

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
题意:

用更快速的方法求上述代码

分析:

通过上面的代码:
我们知道了对于
if[i]=2f[i1]+1i为奇数时:f[i]=2f[i−1]+1
if[i]=2f[i1]i为偶数时:f[i]=2f[i−1]

更希望得到一个可以用一个式子表示的递推式,这样就可以用矩阵快速幂快速求解

通过打表可以得到

f[n]=f[n1]+2f[n2]+1f[n]=f[n−1]+2f[n−2]+1

因此得到关系矩阵

fnfn11=1     2     11     0     00     0     1n1f1f01(38)(38)(fnfn−11)=(1     2     11     0     00     0     1)n−1(f1f01)

code:

//a(n) = a(n-1) + 2*a(n-2) + 1
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,m;
struct Matrix{
    ll mat[4][4];
    Matrix operator * (const Matrix &b)const{
        Matrix ans;
        for(int i = 0; i < 3; i++){
            for(int j = 0; j < 3; j++){
                ans.mat[i][j] = 0;
                for(int k = 0; k < 3; k++){
                    ans.mat[i][j] += mat[i][k] * b.mat[k][j] % m;
                    ans.mat[i][j] %= m;
                }
            }
        }
        return ans;
    }
};

Matrix q_pow(Matrix a,ll b){
    Matrix ans;
    memset(ans.mat,0,sizeof(ans.mat));
    for(int i = 0; i < 3; i++){
        ans.mat[i][i] = 1;
    }
    while(b){
        if(b & 1)
            ans = ans * a;
        b >>= 1;
        a = a * a;
    }
    return ans;
}
int main(){
    while(~scanf("%lld%lld",&n,&m)){
        Matrix ans;
        ans.mat[0][0] = ans.mat[0][2] = ans.mat[1][0] = ans.mat[2][2] = 1;
        ans.mat[1][1] = ans.mat[1][2] = ans.mat[2][0] = ans.mat[2][1] = 0;
        ans.mat[0][1] = 2;
        ans = q_pow(ans,n-1);
        ll ret = (ans.mat[0][0] + ans.mat[0][2]) % m;
        printf("%lld\n",ret);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值