HDU 4565 So Easy!(数学+矩阵快速幂)

来源:互联网 发布:仿真软件multisim14 编辑:程序博客网 时间:2024/06/07 23:43

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status Practice HDU 4565

Description

  A sequence S n is defined as: 

Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate S n
  You, a top coder, say: So easy! 
 

Input

  There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 2 15, (a-1) 2< b < a2, 0 < b, n < 2 31.The input will finish with the end of file.
 

Output

  For each the case, output an integer S n.
 

Sample Input

2 3 1 20132 3 2 20132 2 1 2013
 

Sample Output

4144
 

思路:

http://www.klogk.com/posts/hdu4565/

代码:

#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>#define LL long longLL A,B,n,m;struct Mat{LL num[2][2];Mat(LL x1=0,LL x2=0,LL x3=0,LL x4=0){num[0][0]=x1; num[0][1]=x2;num[1][0]=x3; num[1][1]=x4;}};Mat unit=Mat(1,0,0,1);Mat operator*(const Mat &a,const Mat &b){Mat c;for (long i=0;i<2;++i)for (long j=0;j<2;++j)for (long k=0;k<2;++k)c.num[i][j]=(c.num[i][j]+a.num[i][k]*b.num[k][j]+m)%m;return c;}Mat operator^(const Mat &a,LL n){Mat c=unit,temp=a;while (n){if (n%2) c=temp*c;temp=temp*temp;n/=2;}return c;}Mat wtf;long ans[2];int main(){while (~scanf("%I64d%I64d%I64d%I64d",&A,&B,&n,&m)){ans[0]=2*A;ans[1]=2;wtf=Mat(2*A,-(A*A-B),1,0);wtf=wtf^(n-1);long temp=0;for (long i=0;i<2;++i)temp=(temp+ans[i]*wtf.num[0][i]+m)%m;printf("%d\n",temp);}return 0;}