题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4565
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
#define LL __int64
struct matrix{
LL f[2][2];
};
LL m;
matrix mul(matrix a, matrix b)
{
LL i, j, k;
matrix c;
memset(c.f, 0, sizeof(c.f));
for (i = 0; i<2; i++)
for (j = 0; j<2; j++)
for (k = 0; k<2; k++)
c.f[i][j] = (c.f[i][j] + a.f[i][k] * b.f[k][j]) % m;
return c;
}
matrix pow_mod(matrix e, LL b)
{
matrix s;
s.f[0][0] = s.f[1][1] = 1;
s.f[0][1] = s.f[1][0] = 0;
while (b)
{
if (b%2==1)
s = mul(s, e);
e = mul(e, e);
b/=2;
}
return s;
}
int main()
{
LL a, b, n;
while (scanf("%I64d%I64d%I64d%I64d", &a, &b, &n, &m)!=EOF)
// while(cin>>a>>b>>n>>m)
{
LL p, q, ans;
matrix e;
p = 2 * a;
q = a*a - b;
e.f[0][0] = p; e.f[0][1] = -q;
e.f[1][0] = 1; e.f[1][1] = 0;
e = pow_mod(e, n - 1);
ans = ((p*e.f[0][0] + 2 * e.f[0][1]) % m + m) % m;
printf("%d\n", ans);
}
return 0;
}
本文提供了一个解决特定矩阵运算问题的高效代码实现,包括矩阵乘法、幂运算和模运算。通过使用结构体和自定义函数,简化了复杂矩阵操作的编程过程,并在实际应用中展示了代码的正确性和实用性。
1493

被折叠的 条评论
为什么被折叠?



