1192:放苹果(dp + 搜索)
这道题先用搜索写的,因为我需要先打表来寻找规律。
因为数据量小所以收搜也会过
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int num[20]; int sum, ans; void dfs(int cur, int n, int m) { if (n == sum) { ans++; } else if (cur>m)return; else { for (int i = 1; i <= n; ++i) { if (num[cur - 1] <= i) { sum += i; if (sum <= n){ num[cur] = i; dfs(cur + 1, n, m); } sum -= i; } } } } int main() { int t,n, m; scanf("%d", &t); while (t--) { sum = ans=0; scanf("%d%d", &n, &m); dfs(1, n, m); printf("%d\n", ans); } }
然后:寻找规律,凡是dp和递推题,当想不到动态转移方程时,就应该先打表再推表达式
#include<iostream> #include<cstdio> using namespace std; int dp[20][20]; int main() { //一个盘子,无论苹果 for (int i = 0; i < 20; ++i)dp[i][1] = 1; //0个苹果,无论多个盘子 for (int j = 0; j < 20; ++j)dp[0][j] = 1; for (int i = 1; i < 20;++i) for (int j = 2; j < 20;++j) if (i >= j)dp[i][j] = dp[i][j - 1] + dp[i - j][j]; else dp[i][j] = dp[i][i]; int t, n, m; scanf("%d", &t); while (t--) { scanf("%d%d", &n, &m); printf("%d\n", dp[n][m]); } }