DP Topic 1 Fibonacci Sequence II

topic:

Idea:

        Through Example 3, we can see that after splitting each step we correspond to, we can know that each step calls the repeated calculation we calculated earlier, so here dp[i] , i represents the result of the corresponding Fbn(i), we record it, and when Fbn(i) is needed during the next split, just return the calculated result.

The code is explained in detail below:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
#define endl '\n'
#define int long long
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define All(x) (x).begin(),(x).end()
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10,MOD = 10007;

int dp[N];	

int Fbn(int x)
{
	// 如果 当前 x 即 Fbn(x)  计算过了,
	// 直接返回计算结果
	if(dp[x]) return dp[x] % MOD;

	// 否则递归计算 Fbn(x) ,并记录好 dp
	
	return (dp[x] = Fbn(x - 1) % MOD + Fbn(x - 2) % MOD);
}

inline void solve()
{
	// dp 初始化
	dp[1] = dp[2] = 1;
	
	int n;
	
	cin >> n;
	
	// 计算输出结果
	cout << Fbn(n) % MOD << endl;
	
}


signed main()
{
//	freopen("a.txt", "r", stdin);
	___G;
	int _t = 1;
//	cin >> _t;
	while (_t--)
	{
		solve();
	}

	return 0;
}

Last commit:

Guess you like

Origin blog.csdn.net/hacker_51/article/details/132874362