Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 910 Accepted Submission(s): 247
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!
#include<iostream> #include<cmath> #include<cstring> #include<string> #include<cstdio> using namespace std; __int64 a,b,n,m; __int64 ret[2][2],p[2][2],tmp[2][2]; void init() { ret[0][0]=2*a; ret[0][1]=-(a*a-b); ret[1][0]=1; ret[1][1]=0; p[0][0]=2*a; p[0][1]=-(a*a-b); p[1][0]=1; p[1][1]=0; } void cal1() //矩阵的平方!&1 { int i,j,k; for(i=0;i<2;i++) for(j=0;j<2;j++) { tmp[i][j]=p[i][j]; p[i][j]=0; } for(i=0;i<2;i++) for(j=0;j<2;j++) for(k=0;k<2;k++) p[i][j]=((p[i][j]+tmp[i][k]*tmp[k][j])%m+m)%m; } void cal2() //矩阵的乘法&1 { int i,j,k; for(i=0;i<2;i++) for(j=0;j<2;j++) { tmp[i][j]=ret[i][j]; ret[i][j]=0; } for(i=0;i<2;i++) for(j=0;j<2;j++) for(k=0;k<2;k++) ret[i][j]=((ret[i][j]+tmp[i][k]*p[k][j])%m+m)%m; } void fastmi() { n-=2; while(n) { if(n&1) { cal2(); n--; } else { cal1(); n>>=1; } } } int main() { while(~scanf("%I64d%I64d%I64d%I64d",&a,&b,&n,&m)) { if(n==1) { printf("%I64d\n",2*a%m); continue; } init(); fastmi(); //C1=2*a C0=2 printf("%I64d\n",((ret[0][0]*2*a+ret[0][1]*2)%m+m)%m); } return 0; }