考点
题解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include <bits/stdc++.h>
using namespace std;
int arr[10], ans[55000][10], cnt = -1, N;
void print() { cout << cnt + 1 << endl; for (int i = 0; i <= cnt; ++i, cout << endl) { for (int j = 0; j < 10; ++j) cout << ans[i][j] << " "; } }
void dfs(int idx, int sum) { if (idx > 10 || sum > N) return; if (idx == 10 && sum == N) { copy(arr, arr + 10, ans[++cnt]); return; } for (int i = 1; i <= 3; ++i) { arr[idx] = i; dfs(idx + 1, sum + i); } }
int main() { cin >> N; if (N > 30) cout << "0"; else { dfs(0, 0); if (cnt == -1) cout << "0"; else print(); } return 0; }
|
思路
一道基础的DFS题目
每类配料都有3种选择,一共10类,按道理一共有310种选法,绝对会超时;好在题目只是要求所有类别的配料质量之和
那么只要输入N大于3 * 10 = 30
就是无效的;同时DFS的过程中,和大于N也可以直接退出。两种剪枝操作大大降低了时间复杂度