【PE258】A lagged Fibonacci sequence

【题目链接】

【思路要点】

  • 用Cayley-Hamilton定理优化线性递推。
  • 时间复杂度 O ( N 2 L o g K ) ,其中 N = 2000 , K = 10 18

【代码】


#include<bits/stdc++.h>

using namespace std;
const int MAXN = 4005;
const int P = 20092010;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); } 
template <typename T> void read(T &x) {
  x = 0; int f = 1;
  char c = getchar();
  for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
  for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
  x *= f;
}
template <typename T> void write(T x) {
  if (x < 0) x = -x, putchar('-');
  if (x > 9) write(x / 10);
  putchar(x % 10 + '0');
}
template <typename T> void writeln(T x) {
  write(x);
  puts("");
}
int k, h[MAXN], now[MAXN], res[MAXN];
void times(int *a, int *b) {
  static int tmp[MAXN];
  memset(tmp, 0, sizeof(tmp));
  for (int i = 0; i <= k; i++)
  for (int j = 0; j <= k; j++)
      tmp[i + j] = (tmp[i + j] + 1ll * a[i] * b[j]) % P;
  for (int i = 2 * k; i >= k; i--) {
      tmp[i - 1999] = (tmp[i - 1999] + tmp[i]) % P;
      tmp[i - 2000] = (tmp[i - 2000] + tmp[i]) % P;
      tmp[i] = 0;
  }
  memcpy(a, tmp, sizeof(tmp));
}
int main() {
  k = 2e3;
  for (int i = 1; i <= k; i++)
      h[i] = 1;
  res[0] = now[1] = 1;
  long long n = 1e18;
  n = n + 1 - k;
  while (n != 0) {
      if (n & 1) times(res, now);
      n >>= 1; times(now, now);
  }
  for (int i = k + 1; i <= 2 * k; i++)
      h[i] = (h[i - 1999] + h[i - 2000]) % P;
  int ans = 0;
  for (int i = 0; i <= k - 1; i++)
      ans = (ans + 1ll * res[i] * h[i + k]) % P;
  writeln(ans);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39972971/article/details/80861705