HDU 2256 Problem of Precision(矩陣快速冪)

Problem Description

 

Input
The first line of input gives the number of cases, T. T test cases follow, each on a separate line. Each test case contains one positive integer n. (1 <= n <= 10^9)
 

Output
For each input case, you should output the answer in one line.
 

Sample Input
3 1 2 5
 

Sample Output
9 97 841
 
分析:令x=sqrt(6) 向下取整的做法就是構造f(n)=An+Bn*x 
遞推An和Bn  最後發現An和Bn的關係由於向下取整,所以答案即爲2*An-1
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<string>
#include<iostream>
#include<queue>
#include<cmath>
#include<map>
#include<stack>
#include<bitset>
using namespace std;
#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )
#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )
#define CLEAR( a , x ) memset ( a , x , sizeof a )
typedef long long LL;
typedef pair<int,int>pil;
const int INF = 0x3f3f3f3f;
const int mod=1024;
LL n;
struct Matrix{
    LL mat[2][2];
    void Clear()
    {
        CLEAR(mat,0);
    }
};
Matrix mult(Matrix m1,Matrix m2)
{
    Matrix ans;
    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
        {
            ans.mat[i][j]=0;
            for(int k=0;k<2;k++)
                ans.mat[i][j]=(ans.mat[i][j]+m1.mat[i][k]*m2.mat[k][j])%mod;
        }
    return ans;
}
Matrix Pow(Matrix m1,LL b)
{
    Matrix ans;ans.Clear();
    for(int i=0;i<2;i++)
        ans.mat[i][i]=1;
    while(b)
    {
        if(b&1)
            ans=mult(ans,m1);
        b>>=1;
        m1=mult(m1,m1);
    }
    return ans;

}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%I64d",&n);
        LL p=5LL,q=2LL;//x^n+y^n
        Matrix A;
        if(n==1)
        {
            printf("%I64d\n",p*2-1);
            continue;
        }
        A.mat[0][0]=5;A.mat[0][1]=12;
        A.mat[1][0]=2;A.mat[1][1]=5;
        A=Pow(A,n-1);
        LL ans=(A.mat[0][0]*p+A.mat[0][1]*q)%mod;
        ans=ans*2%mod-1;
        printf("%I64d\n",ans);
    }
    return 0;
}


發佈了434 篇原創文章 · 獲贊 5 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章