Construct a Matrix (矩阵快速幂+构造)
1. The matrix is a S(n)×S(n) matrix;
2. S(n) is the sum of the first n Fibonacci numbers modulus m, that is S(n) = (F1 + F2 + … + Fn) % m;
3. The matrix contains only three kinds of integers ‘0’, ‘1’ or ‘-1’;
4. The sum of each row and each column in the matrix are all different.
Here, the Fibonacci numbers are the numbers in the following sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
By definition, the first two Fibonacci numbers are 1 and 1, and each remaining number is the sum of the previous two.
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2, with seed values F1 = F2 = 1.
Given two integers n and m, your task is to construct the matrix.
Input
Output
Sample Input
2 2 3 5 2
Sample Output
Case 1: Yes -1 1 0 1 Case 2: No
难点在于构造:
构造方式 下三角为-1,上三角为 1,主对角-1 0 排列 ,主要是奇数和0的也不存在
代码:
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<queue> #include<stack> #include<set> #include<vector> #include<map> #include<cmath> const int maxn=1e5+5; typedef long long ll; using namespace std; struct Mat { ll a[4][4]; }; int mod; Mat Mul(Mat a,Mat b) { Mat ans; memset(ans.a,0,sizeof(ans.a)); for(int t=0;t<3;t++) { for(int j=0;j<3;j++) { for(int k=0;k<3;k++) { ans.a[t][j]=(ans.a[t][j]+a.a[t][k]*b.a[k][j])%mod; } } } return ans; } Mat ans; ll quickpow(int n) { Mat res; res.a[0][0]=1; res.a[0][1]=1; res.a[0][2]=1; res.a[1][0]=0; res.a[1][1]=1; res.a[1][2]=1; res.a[2][0]=0; res.a[2][1]=1; res.a[2][2]=0; while(n) { if(n&1) { ans=Mul(res,ans); } res=Mul(res,res); n>>=1; } return ans.a[0][0]; } int main() { int T; cin>>T; int n; int cnt=1; while(T--) { scanf("%d%d",&n,&mod); memset(ans.a,0,sizeof(ans.a)); ans.a[0][0]=2; ans.a[1][0]=1; ans.a[2][0]=1; ll aa=quickpow(n-2)%mod; if(aa&1||aa==0) { printf("Case %d: No\n",cnt++); } else { printf("Case %d: Yes\n",cnt++); for(int t=0;t<aa;t++) { for(int j=0;j<aa;j++) { if(t>j) { printf("-1 "); } if(t<j) { printf("1 "); } if(t==j&&t%2==0) { printf("-1 "); } if(t==j&&t%2==1) { printf("0 "); } } printf("\n"); } } } return 0; }
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步