hdu4565 矩阵构造+矩阵快速幂

来源:互联网 发布:淘宝上levis眼镜 编辑:程序博客网 时间:2024/05/17 11:04

第一眼看到就是矩阵快速幂,当然不能拿浮点数来快速幂了,要转化一下。

看到一些乱七八糟的推导,下面来个简单的



下面就直接快速幂就好了

//  Created by Chenhongwei on 2016-03-02 Wednesday 23:48//  Copyright (c) 2016 Chenhongwei. All rights reserved.#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <climits>#include <queue>#include <cmath>#include <map>#include <set>#include <stack>#include <vector>#include <sstream>#include <algorithm>#define root 1,n,1#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1using namespace std;const int inf=1e9;const int maxn=1e5+100;typedef long long ll;typedef unsigned long long ull;struct matrix{int x[2][2];};ll a,b,n,mod;matrix mul(matrix &A,matrix &B){matrix C;for(int i=0;i<2;i++)for(int j=0;j<2;j++){C.x[i][j]=0;for(int k=0;k<2;k++)C.x[i][j]=(C.x[i][j]+A.x[i][k]*B.x[k][j]%mod)%mod;}return C;}int main(){//ios::sync_with_stdio(false);    // freopen("in.txt","r",stdin);//freopen("out.txt","w",stdout);while(scanf("%lld%lld%lld%lld",&a,&b,&n,&mod)!=EOF){matrix ans,t;for(int i=0;i<2;i++)for(int j=0;j<2;j++)ians.x[i][j]=(i==j);t.x[0][0]=a%mod,t.x[0][1]=1;t.x[1][0]=b%mod,t.x[1][1]=a%mod;while(n){if(n&1)ans=mul(ans,t);t=mul(t,t);n>>=1;}printf("%lld\n",(ans.x[0][0]*2)%mod);}return 0;}



0 0
原创粉丝点击