hdu4565矩阵快速幂

这题太坑了。。。刚开始以为可以用|a+sqrt(b)  1|水过。。。结果tle,还一直想明明我logn的做法怎么可能tle。。

                                             |    0           1|

实在无奈看的题解 (a+sqrt(b))^n=x+y*sqrt(b);  (a+sqrt(b))^(n+1)=a*x+b*y+(x+a*y)*sqrt(b)

这样可以构造矩阵|a  b|    *   |x|

                       |1  b|         |y|

还有记得矩阵乘法%m

最后还有一个坑就是

   (a-1)^2<b<a^2 ,
  0 < ( a - sqrt( b ) )^ n < 1
  ( a + sqrt( b ) )^ n + ( a - sqrt( b ) )^ n = 2 * Xn
  ( a + sqrt( b ) )^ n 向上取整的值就是 2 * Xn(不用会超时@_@)
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<iomanip>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define ll long long
#define mod 10
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1
#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;

const double g=10.0,eps=1e-9;
const int N=10+5,maxn=1<<10+5,inf=0x3f3f3f3f;

struct Node{
    ll row,col;
    ll a[N][N];
};
ll m;
Node mul(Node x,Node y)
{
    Node ans;
    ans.row=x.row,ans.col=y.col;
    memset(ans.a,0,sizeof ans.a);
    for(ll i=0;i<x.row;i++)
        for(ll j=0;j<x.col;j++)
            for(ll k=0;k<y.col;k++)
                ans.a[i][k]=(ans.a[i][k]+x.a[i][j]*y.a[j][k])%m;
    return ans;
}
Node quick_mul(Node x,ll n)
{
    Node ans;
    ans.row=x.row,ans.col=x.col;
    memset(ans.a,0,sizeof ans.a);
    for(ll i=0;i<ans.col;i++)ans.a[i][i]=1;
    while(n){
        if(n&1)ans=mul(ans,x);
        x=mul(x,x);
        n>>=1;
    }
    return ans;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
 //   cout<<setiosflags(ios::fixed)<<setprecision(2);
    ll a,b,n;
    while(cin>>a>>b>>n>>m){
        Node A;
        A.row=2,A.col=2;
        A.a[0][0]=a,A.a[0][1]=b;
        A.a[1][0]=1,A.a[1][1]=a;
        A=quick_mul(A,n);
        ll ans=A.a[0][0]*2;
        cout<<ans%m<<endl;
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/acjiumeng/p/6872958.html