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

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

题意:

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

分析:

通过上面的代码:
我们知道了对于
i f [ i ] = 2 f [ i 1 ] + 1
i f [ i ] = 2 f [ i 1 ]

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

通过打表可以得到

f [ n ] = f [ n 1 ] + 2 f [ n 2 ] + 1

因此得到关系矩阵

(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 <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;
}

猜你喜欢

转载自blog.csdn.net/codeswarrior/article/details/82526404