您的位置:首页 > 其它

HDU 4565 So Easy!

2016-03-10 16:50 381 查看

So Easy!

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3459 Accepted Submission(s): 1113


[align=left]Problem Description[/align]
  A sequence Sn 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 Sn.
  You, a top coder, say: So easy!



[align=left]Input[/align]
  There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 215, (a-1)2< b < a2, 0 < b, n < 231.The input will finish with the end of file.

[align=left]Output[/align]
  For each the case, output an integer Sn.

[align=left]Sample Input[/align]

2 3 1 2013

2 3 2 2013

2 2 1 2013

[align=left]Sample Output[/align]

4

14

4

[align=left]Source[/align]
2013 ACM-ICPC长沙赛区全国邀请赛——题目重现

解析:矩阵快速幂
根据共轭式的原理,(a+√b)n+(a-√b)n必为整数。
而(a-1)2< b < a2
=> a-1< √b < a
=> 0< a-√b <1
=> 0< (a-√b)n <1
所以(a+√b)n+(a-√b)n = ceil( (a+√b)n )。



接下来就可以运用矩阵快速幂求解。

#include <cstdio>
#include <cstring>

long long a,b,n,m;

struct Mat1{
long long mat[2][2];
};

struct Mat2{
long long mat[2][1];
};

Mat1 operator * (Mat1 A,Mat1 B)
{
Mat1 ret;
memset(ret.mat,0,sizeof(ret));
for(int i = 0; i<2; ++i)
for(int j = 0; j<2; ++j)
for(int k = 0; k<2; ++k)
ret.mat[i][j] = (ret.mat[i][j]+A.mat[i][k]*B.mat[k][j])%m;
return ret;
}

Mat2 operator * (Mat1 A,Mat2 B)
{
Mat2 ret;
memset(ret.mat,0,sizeof(ret));
for(int i = 0; i<2; ++i)
for(int j = 0; j<1; ++j)
for(int k = 0; k<2; ++k)
ret.mat[i][j] = (ret.mat[i][j]+A.mat[i][k]*B.mat[k][j])%m;
return ret;
}

void matquickpowmod()
{
Mat1 x;
x.mat[0][0] = 2*a;
x.mat[0][1] = b-a*a;
x.mat[1][0] = 1;
x.mat[1][1] = 0;
Mat2 y;
y.mat[0][0] = 2*a;
y.mat[1][0] = 2;
while(n){
if(n&1)
y = x*y;
x = x*x;
n >>= 1;
}
printf("%I64d\n",(y.mat[1][0]%m+m)%m);
}

int main()
{
while(~scanf("%I64d%I64d%I64d%I64d",&a,&b,&n,&m)){
matquickpowmod();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: