题解 | #递归函数的次数#

递归函数的次数

https://ac.nowcoder.com/acm/problem/24665

考察知识点:递归、滚动数组

递归函数调用次数满足递推式 an=an1+an2+an3+1a_n = a_{n-1} + a_{n-2} + a_{n-3} + 1,其中 a1=a2=a3=1a_1 = a_2 = a_3 = 1。 由于 n100,000,000n \leq 100,000,000,所以不能直接递归或者迭代求解,考虑使用滚动数组优化。

时间复杂度O(n)O(n)

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vpii;
typedef vector<pll> vpll;

#define MOD 1000000

int a[5] = {0, 1, 1, 1};

void solve()
{
    int n;
    cin >> n;
    if (n < 4)
    {
        cout << a[n] << endl;
        return;
    }
    for (int i = 4; i <= n; i++)
    {
        a[4] = (a[1] + a[2] + a[3] + 1) % MOD;
        a[1] = a[2];
        a[2] = a[3];
        a[3] = a[4];
    }
    cout << a[4] << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t = 1;
    // cin >> t;
    while (t--)
        solve();
    return 0;
}
全部评论
???现在就写题解不被看光光
1 回复 分享
发布于 2023-07-31 21:28 山西

相关推荐

不知道怎么取名字_:玩游戏都写到简历上了啊
点赞 评论 收藏
分享
喵_coding:年底缺人是短视频营造出来的 而且一般说的也很宽泛 不是特指后端
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务