您的位置:首页 > 其它

hdoj 4565 So Easy!(构造无理数共轭,矩阵快速幂)

2016-10-13 20:53 441 查看
最难的是要想到无理数共轭...

参考题解:点击打开链接

还要注意注意负数的取模,可以先+mod再进行取模.



代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a, b, m;
struct node
{
ll s[2][2];
node() {}
node(ll a, ll b, ll c, ll d)
{
s[0][0] = a;
s[0][1] = b;
s[1][0] = c;
s[1][1] = d;
}
};

node mul(node a, node b)
{
node t = node(0, 0, 0, 0);
for(int i = 0; i < 2; i++)
for(int j = 0; j < 2; j++)
for(int k = 0; k < 2; k++)
t.s[i][j] = (t.s[i][j]+a.s[i][k]*b.s[k][j]+m)%m;    //注意负数
return t;
}

node mt_pow(node p, int n)
{
node q = node(1, 0, 0, 1);
while(n)
{
if(n&1) q = mul(p, q);
p = mul(p, p);
n /= 2;
}
return q;
}

int main(void)
{
ll n;
while(cin >> a >> b >> n >> m)
{
node base = node(2*a, (b-a*a), 1, 0);
ll c1 = 2*a%m;
ll c2 = 2*(a*a+b)%m;
if(n == 1) printf("%lld\n", c1);
else if(n == 2) printf("%lld\n", c2);
else
{
node ans = mt_pow(base, n-2);
printf("%lld\n", (ans.s[0][0]*c2+ans.s[0][1]*c1+m)%m);
}
}
return 0;
}



So Easy!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 3883    Accepted Submission(s): 1279


Problem Description

  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! 



 

Input

  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.

 

Output

  For each the case, output an integer Sn.

 

Sample Input

2 3 1 2013
2 3 2 2013
2 2 1 2013

 

Sample Output

4
14
4

 

Source

2013
ACM-ICPC长沙赛区全国邀请赛——题目重现

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息