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

Reading comprehension HDU - 4990

 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=(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]+1 i 为 奇 数 时 : f [ i ] = 2 f [ i − 1 ] + 1
if[i]=2f[i1] i 为 偶 数 时 : f [ i ] = 2 f [ i − 1 ]

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

通过打表可以得到

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

因此得到关系矩阵

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

code:

//a(n) = a(n-1) + 2*a(n-2) + 1
#include 
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;
}

你可能感兴趣的:(矩阵快速幂)