官方题解 | 时空の穿越
2025-04-12 18:28:22
发布于:云南
47阅读
0回复
0点赞
T4 时空の穿越:矩阵
题意简化
给定序列 ,有:
求 ,其中:
暴力代码
很显然的一个递推式子。直接模拟一下即可。
#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long
ull _,n;
ull dp[1005];
int main(){
cin>>_;
while(_--){
cin>>n;
dp[1]=dp[2]=dp[3]=dp[4]=dp[5]=1;
for(ull i=6;i<=n;i++) dp[i]=
dp[i-1]+
(dp[i-2]<<1)+
(dp[i-3]<<1)+dp[i-3]+
(dp[i-4]<<2)+dp[i-4]+
(dp[i-5]<<3);
cout<<(int)dp[n]<<'\n';
}
return 0;
}
时间复杂度:
空间复杂度:
预计得分:
空间优化
显然 只与 有关。所以我们只需要记录 个数即可。
#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long
ull _,n,a,b,c,d,e,t;
int main(){
cin>>_;
while(_--){
cin>>n;
a=b=c=d=e=1;
for(ull i=6;i<=n;i++){
t=a;
a=b;
b=c;
c=d;
d=e;
e+=(c<<1)+(b<<1)+b+(a<<2)+a+(t<<3);
}
cout<<(int)e<<'\n';
}
return 0;
}
时间复杂度:
空间复杂度:
预计得分:
正解
由线性递推联想到矩阵加速。
回忆一下斐波那契数列的矩阵加速:定义矩阵:
得到:
根据矩阵乘法,得到:
所以得到:
于是问题转化为:
矩阵快速幂即可。
类似地,我们定义矩阵:
得到:
根据矩阵乘法,得到:
所以得到:
于是问题转化为:
矩阵快速幂即可。
#include<bits/stdc++.h>
using namespace std;
#define uint unsigned int
#define ull unsigned long long
#define rep(i,l,r) for(int i=l;i<=r;i++)
struct mat{
int n,m;
uint a[7][7];
inline void empty(){
this->n=this->m=0;
memset(this->a,0,sizeof(this->a));
return;
}
inline void resize(const int &n,const int &m){
empty();
this->n=n,this->m=m;
return;
}
inline void unit(const int &n){
empty();
this->n=this->m=n;
rep(i,1,n) this->a[i][i]=1;
return;
}
inline void fill(const int &x){
rep(i,1,this->n) rep(j,1,this->m) this->a[i][j]=x;
return;
}
inline mat operator*(const mat &a){
mat res;
res.resize(this->n,a.m);
rep(i,1,res.n) rep(j,1,res.m) rep(k,1,this->m) res.a[i][j]+=this->a[i][k]*a.a[k][j];
return res;
}
inline void operator*=(const mat &a){
*this=*this*a;
return;
}
};
int _;
ull n;
mat x,y,res;
int main(){
cin>>_;
while(_--){
cin>>n;
if(n>5) n-=5;
else{
cout<<"1\n";
continue;
}
x.resize(5,1);
x.fill(1);
y.resize(5,5);
y.a[1][1]=y.a[2][1]=y.a[3][2]=y.a[4][3]=y.a[5][4]=1;
y.a[1][2]=2,y.a[1][3]=3,y.a[1][4]=5,y.a[1][5]=8;
res.unit(5);
while(n){
if(n&1) res*=y;
y*=y;
n>>=1;
}
res*=x;
cout<<(int)(res.a[1][1])<<'\n';
}
return 0;
}
时间复杂度:
空间复杂度:
预计得分:
全部评论 1
初中同学表示不理解
2025-04-13 来自 浙江
0不理解的可以看这个
https://www.acgo.cn/problemset/37635/36199?tab=explanation2025-04-13 来自 广东
1OK
2025-04-13 来自 浙江
0没学过是这样的。先去学一下矩阵吧
1周前 来自 北京
0
有帮助,赞一个