- 下楼梯 6级1 2023样卷
- 2024-06-16 18:08:06 @
#include <bits/stdc++.h>
using namespace std;
inline void print(__int128 x)
{
if(x>9)print(x/10);
putchar(x%10+'0');
}
__int128 f(int n)
{
if(!n)return 1;
if(n==1)return 1;
if(n==2)return 2;
else return f(n-1)+f(n-2)+f(n-3);
}
int main()
{
ios::sync_with_stdio(false);
int n;
cin>>n;
__int128 ans=f(n);
print(ans);
return 0;
}
超时(永不变的超时问题)
3 条评论
-
Infinity_ LV 8 @ 2024-06-26 13:01:46
递推比递归的办法效率高
-
2024-06-16 19:11:53@
给你改了一下,你的程序超时是因为递归有冗余计算,所以加一个记忆化就行了。建议这题改成递推,不仅代码短,也不会超时。
-
2024-06-16 19:10:26@
#include <bits/stdc++.h> #define __int128 long long using namespace std; __int128 a[105]; inline void print(__int128 x) { if(x>9)print(x/10); putchar(x%10+'0'); } __int128 f(int n) { if(!n)return 1; if(n==1)return 1; if(n==2)return 2; if(a[n]!=-1)return a[n]; else return a[n]=f(n-1)+f(n-2)+f(n-3); } int main() { ios::sync_with_stdio(false); int n; cin>>n; for(int i=1;i<=n;i++) a[i]=-1; print(f(n)); return 0; }
- 1
信息
- ID
- 2611
- 难度
- 7
- 分类
- (无)
- 标签
- 递交数
- 102
- 已通过
- 20
- 通过率
- 20%
- 上传者