洛谷P1192 台阶问题【记忆化搜索】

题目https://www.luogu.org/problemnew/show/P1192

题意:

给定n和k,一个人一次可以迈1~k步,问走n步有多少种方案。

思路:

本来傻乎乎上来就递归,显然会T的啊猪头!

然后改成记忆化搜索。dfs的参数就是还剩余的步数,num数组存的就是走i步的方案数。

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<map>
 4 #include<set>
 5 #include<iostream>
 6 #include<cstring>
 7 #include<algorithm>
 8 #include<vector>
 9 #include<cmath> 
10 #include<queue>
11 
12 #define inf 0x7f7f7f7f
13 using namespace std;
14 typedef long long LL;
15 typedef pair<int, int> pr;
16 
17 int n, k;
18 //int ans = 0;
19 const int mod = 100003;
20 const int maxn = 1e5 + 5; 
21 LL num[maxn];
22 
23 LL dfs(int x)
24 {
25     if(x < 0)return 0;
26     else if(num[x])return num[x];
27     else if(x == 0)return 1;
28     
29     LL ans = 0;
30     for(int i = 1; i <= k; i++){
31         ans = (ans + dfs(x - i)) % mod;
32     }
33     num[x] = ans;
34     return num[x];
35 }
36 
37 int main()
38 {
39     memset(num, 0, sizeof(num));
40     scanf("%d%d", &n, &k);
41     printf("%lld\n", dfs(n));
42     
43     return 0;
44 }

猜你喜欢

转载自www.cnblogs.com/wyboooo/p/10380972.html