华为机试
公司分月饼,m个员工,买了n个月饼,m <= n,每个员工至少分一个月饼,但是也可以分到多个,单人分到最多月饼的个数是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
输出描述:
输出有多少种分法
示例1:
输入
2 4
输出
2
说明
4=1+3
4=2+2
注意:1+3和3+1要算成同一种分法
示例2:
输入
3 5
输出
2
说明
5=1+1+3
5=1+2+3
示例3:
输入
3 12
输出
6
说明
满足要求的6种分法:
1、12 = 1 + 1 + 10 (Max1=10, Max2=1,不满足Max1-Max2 <= 3的约束)
2、12 = 1 + 2 + 9 (Max1=9,Max2=2,不满足Max1-Max2 <= 3的约束)
3、12 = 1 + 3 + 8 (Max1=8,Max2=3,不满足Max1-Max2 <= 3的约束)
4、12 = 1 + 4 + 7 (Max1=7,Max2=4,Max3=1, 满足要求)
5、12 = 1 + 5 + 6 (Max1=6,Max2=5,Max3=1, 不满足要求)
6、12 = 2 + 2 + 8 (Max1=8,Max2=2,不满足要求)
7、12 = 2 + 3 + 7 (Max1=7,Max2=3,不满足要求)
8、12 = 2 + 4 + 6 (Max1=6,Max2=4,Max3=2, 满足要求)
9、12 = 2 + 5 + 5 (Max1=5,Max2=2 满足要求)
10、12 = 3 + 3 + 6 (Max1=6,Max2=3 满足要求)
11、12 = 3 + 4 + 5 (Max1=5,Max2=4,Max3=3 满足要求)
12 = 4 + 4 + 4 (Max1=4,满足要求)
————————————————
#include<stdio.h>
#include<malloc.h>
#include<string.h>
//m个月饼放在n个人,没人至少一个且max1-max2<=3 max2=-max3<=3......
const int N = 3;
const int M = 10;
int *path = (int*)malloc(sizeof(int)*N);
int pathcount = 0;
int**result = (int**)malloc(sizeof(int)*N*M);
int resultcount = 0;
int getnum()
{
int sum = 0;
for (size_t i = 0; i < pathcount; i++)
{
sum += path[i];
}
return M - N - sum;
}
//对m-n 进行回溯
void back(int num)
{
if (pathcount==N)
{
if (getnum() == 0)
{
result[resultcount] = (int*)malloc(sizeof(int)*N);
memcpy(result[resultcount], path, sizeof(int)*N);
resultcount++;
}
return;
}
for (int i = num; i >=0; i--)
{
path[pathcount++] = i;
int inum = getnum();
if (inum > i)
{
inum = i;
}
else
{
if (i -inum > 3)
{
path[--pathcount];
continue;
}
}
back(inum);
path[--pathcount];
}
}
void printfresult()
{
for (size_t i = 0; i < resultcount; i++)
{
for (size_t j = 0; j < N; j++)
{
printf("%d ", result[i][j]);
}
printf("\n");
}
}
int main()
{
memset(path, 0, sizeof(int)*N);
back(M - N);
printfresult();
return 0;
}