题目描述
中秋节,公司分月饼,m 个员工,买了 n 个月饼,m ≤ n,每个员工至少分 1 个月饼,但可以分多个,
- 单人分到最多月饼的个数是 Max1 ,单人分到第二多月饼个数是 Max2 ,Max1 - Max2 ≤ 3 ,
- 单人分到第 n - 1 多月饼个数是 Max(n-1),单人分到第n多月饼个数是 Max(n) ,Max(n-1) – Max(n) ≤ 3,
问有多少种分月饼的方法?
输入描述
每一行输入m n,表示m个员工,n个月饼,m ≤ n
输出描述
输出有多少种月饼分法
用例
| 输入 | 2 4 |
|---|---|
| 输出 | 2 |
| 说明 | 分法有2种: 4 = 1 + 3 4 = 2 + 2 注意:1+3和3+1算一种分法 |
| 输入 | 3 5 |
|---|---|
| 输出 | 2 |
| 说明 | 5 = 1 + 1 + 3 5 = 1 + 2 + 2 |
| 输入 | 3 12 |
|---|---|
| 输出 | 6 |
| 说明 | 满足要求的有6种分法: 12 = 1 + 1 + 10(Max1 = 10, Max2 = 1,不满足Max1 - Max2 ≤ 3要求) 12 = 1 + 2 + 9(Max1 = 9, Max2 = 2,不满足Max1 - Max2 ≤ 3要求) 12 = 1 + 3 + 8(Max1 = 8, Max2 = 3,不满足Max1 - Max2 ≤ 3要求) 12 = 1 + 4 + 7(Max1 = 7, Max2 = 4,Max3 = 1,满足要求) 12 = 1 + 5 + 6(Max1 = 6, Max2 = 5,Max3 = 1,不满足要求) 12 = 2 + 2 + 8(Max1 = 8, Max2 = 2,不满足要求 )12 = 2 + 3 + 7(Max1 = 7, Max2 = 3,不满足要求) 12 = 2 + 4 + 6(Max1 = 6, Max2 = 4,Max3 = 2,满足要求) 12 = 2 + 5 + 5(Max1 = 5, Max2 = 2,满足要求) 12 = 3 + 3 + 6(Max1 = 6, Max2 = 3,满足要求) 12 = 3 + 4 + 5(Max1 = 5, Max2 = 4,Max3 = 3,满足要求) 12 = 4 + 4 + 4(Max1 = 4,满足要求) |
思路
dfs
#include <iostream>
int res, m; // m个员工,n个月饼
// 四个参数分别代表,
// 第pos位员工
// 此时剩余的月饼数量
// 最多分到的数量和最少分到的数量
// 那么,第pos+1 个人获得的月饼数量的范围x1一定有
// x ≤ x1 ≤ min(sum − x, x + 3) 如果pos==m,且sum=0,则找到了,res+=1
void dfs(int pos, int sum, int minimum, int maximum)
{
if (pos == m)
{
if (sum == 0) {
res++;
}
return;
}
if (minimum > sum || sum < 0 || maximum < minimum)
{
return; // 不合法的情况
}
for (int i = minimum; i <= maximum; i++) // 枚举下一个人获得的月饼数量
{
dfs(pos + 1, sum - i, i, std::min(sum - i, i + 3));
}
}
int main31()
{
int n;
std::cin >> m >> n;
dfs(0, n, 1, n);
std::cout << res << std::endl;
return 0;
}