HDU4565 So Easy! 矩阵快速幂
题目链接
题目
思路
因为\((a-1)^{2}<b<a^2\),所以\((a-1)<\sqrt b < a\),因此\(a-\sqrt b < 1\),从而有\((a-\sqrt b)^{n}<1\)。
设\(C_{n}=(a+\sqrt b)^n+(a-\sqrt b)^n\),由上一段可以得知\(\lceil C_{n}\rceil = S_n\)。
又\(2aC_n=((a-\sqrt b)+(a+\sqrt b))C_n=(a-\sqrt b)C_n+(a+\sqrt b)C_n=C_{n+1}+(a^2-b)C_{n-1}\)。
因此\(C_n\)具有线性递推式\(C_n=2aC_{n-1}+(b-a^2)C_{n-2}\)。
代码实现如下
#include <set>
#include <map>
#include <deque>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <bitset>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL, LL> pLL;
typedef pair<LL, int> pLi;
typedef pair<int, LL> piL;;
typedef pair<int, int> pii;
typedef unsigned long long uLL;
#define lson rt<<1
#define rson rt<<1|1
#define lowbit(x) x&(-x)
#define name2str(name) (#name)
#define bug printf("*********\n")
#define debug(x) cout<<#x"=["<<x<<"]" <<endl
#define FIN freopen("in","r",stdin)
#define IO ios::sync_with_stdio(false),cin.tie(0)
const double eps = 1e-8;
const int mod = 1e9 + 7;
const int maxn = 1e6 + 7;
const double pi = acos(-1);
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3fLL;
int n, m, x, y;
int f[5], a[5][5];
void mulself(int a[5][5]) {
int c[5][5];
memset(c, 0, sizeof(c));
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
c[i][j] = (c[i][j] + (long long)a[i][k] * a[k][j]) % m;
}
}
}
memcpy(a, c, sizeof(c));
}
void mul(int f[5], int a[5][5]) {
int c[5];
memset(c, 0, sizeof(c));
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
c[i] = (c[i] + (long long)f[j] * a[j][i] ) % m;
}
}
memcpy(f, c, sizeof(c));
}
int main() {
while(~scanf("%d%d%d%d", &x, &y, &n, &m)) {
f[0] = (LL)ceil((x * x % m + y) % m + 2 * x * sqrt(y)) % m, f[1] = 2 * x % m;
if(n == 1) {
printf("%d\n", f[1]);
continue;
} else if(n == 2) {
printf("%d\n", f[0]);
continue;
}
a[0][0] = 2 * x, a[0][1] = 1;
a[1][0] = ((y - x * x) % m + m) % m, a[1][1] = 0;
n -= 2;
while(n) {
if(n & 1) mul(f, a);
mulself(a);
n >>= 1;
}
printf("%d\n", f[0] % m);
}
return 0;
}
版权声明:本文允许转载,转载时请注明原博客链接,谢谢~