HDU6030 Happy Necklace

推导或者可以找规律有公式:\(f[n] = f[n-1] + f[n-3]\) 。

构造矩阵乘法:

\[\begin{pmatrix} f_i \\ f_{i-1} \\ f_{i-2} \end{pmatrix} = \begin{pmatrix} 1 & 0 & 1 \\ 1 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix}\begin{pmatrix} f_{i-1} \\ f_{i-2} \\ f_{i-3} \end{pmatrix}
\]

时间复杂度为 \(O(\log n)\) 。

#include<bits/stdc++.h>

using namespace std;

const int mod = 1e9 + 7;
int t;
long long n;
struct Matrix{
long long a[5][5];
}; Matrix mul(Matrix M1, Matrix M2)
{
Matrix ret;
memset(ret.a, 0, sizeof(ret.a));
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
for(int k = 0; k < 3; k++){
ret.a[i][j] = (M1.a[i][k] * M2.a[k][j] + ret.a[i][j]) % mod;
}
}
}
return ret;
}
void matrix_pow(long long x)
{
Matrix ret;
memset(ret.a, 0, sizeof(ret.a));
for(int i = 0; i < 3; i++) ret.a[i][i] = 1;
Matrix tmp;
memset(tmp.a, 0, sizeof(tmp.a));
tmp.a[0][0] = tmp.a[0][2] = tmp.a[1][0] = tmp.a[2][1] = 1;
while(x){
if(x & 1LL) ret = mul(ret, tmp);
tmp = mul(tmp, tmp);
x >>= 1LL;
}
long long ans = (ret.a[0][0] * 4 + ret.a[0][2] * 2 + ret.a[0][1] * 3) % mod;
cout << ans << endl;
}
int main()
{
for(scanf("%d", &t); t--; ){
scanf("%lld", &n);
if(n == 1) {puts("2"); continue;}
else if(n == 2) {puts("3"); continue;}
else if(n == 3) {puts("4"); continue;}
else{
matrix_pow(n - 3);
}
}
return 0;
}

最新文章

  1. Seo标签权重
  2. xmind8
  3. js原生捕鱼达人(一)
  4. POJ 2217 (后缀数组+最长公共子串)
  5. leetcode:Integer to Roman(整数转化为罗马数字)
  6. [转载]关于AutoCAD.NET的辅助方法
  7. 只响应ccTouchBegan的问题
  8. java.lang.IllegalAccessError: class javax.activation.SecuritySupport12 cannot access its superclass
  9. poj2431 Expedition
  10. AES加解密算法Qt实现
  11. 【转】5 Best Place to Learn Linux – Linux Tutorial Sites
  12. 2018-2019-2 20175234 实验二《Java面向对象程序设计》实验报告
  13. java框架之SpringBoot(16)-分布式及整合Dubbo
  14. freopen stdout 真的更快?
  15. 数据库实例: STOREBOOK &gt; 表空间 &gt; 编辑 表空间: UNDOTBS1
  16. 02 - Unit08:搜索笔记功能、搜索分页、处理插入数据库乱码问题
  17. scala(三)
  18. C# Selenium with PhantomJSDriver get image width and height (获取图片的长和高)
  19. 136. Single Number唯一的数字
  20. 国内Windows系统go get语言包

热门文章

  1. SCUT - 482 - 生成树上的点 - Prufer
  2. 2、Java调用C语言(JNative法)
  3. grep 查找文件
  4. Django【第9篇】:Django之用户认证auth模块
  5. git-bash下, 启动sshd
  6. js学习之BOM和DOM
  7. 过采样算法之SMOTE
  8. 快速幂(Fast Pow)
  9. note 2019.12.16
  10. 【GDOI2014模拟】服务器