A piece of cake
This problem is very simple, i.e. just a piece of cake for you, excellent programmers. You just need to calculate and output how many ways to put n different balls into m different boxes so that each box has at least k balls.
Input:
Input contains several test cases. Each of the test cases contains three integers in one line, n, m, k(1<=n, m<=15, 0<=k<=15). Input is terminated by three 0’s, which should not be processed.
Output:
For each case, just print the result in one line. Heading zeros are forbidden. For example, 12 is legal output but 012 is not, 0 is legal but 00 is not, and so on.
Sample input:
3 3 1
2 4 1
3 2 0
0 0 0
Sample output:
6
0
8
解题分析:
n个不同的球放在m个不同的盒子里,每个盒子至少放k个球,用fn(n,m,k)表示
方法数,用fc(n,i)表示下标为n,上标为i的组合数值。不难得出有以下关系式:
n
fn(n,m,k)=∑fc(n,i)*fn(n-i,m-1,k).
i=k
程序代码为:
#include<iostream>
#include<fstream>
using namespace std;
int ball_num,box_num,least_num;
int addition(int n,int i)
{
int sum1=1,sum2=1;
for(int j=n;j>=(n-i+1);j--)
{
sum1*=j;
}
for(int k=1;k<=i;k++)
{
sum2*=k;
}
return sum1/sum2;
}
int method_num(int ball,int box,int least)
{
if(least>0&&(ball/least)<box)
{
return 0;
}
else
{
if(box-1==0)
{
return 1;
}
else
{ int sum=0;
for(int i=least;i<=ball;i++)
{
sum+=addition(ball,i)*method_num(ball-i,box-1,least);
}
return sum;
}
}
}
void main()
{
ifstream stream("input.txt");
while(!stream.eof())
{
stream>>ball_num>>box_num>>least_num;
if(ball_num==0&&box_num==0&&least_num==0)
{
break;
}
else
{
cout<<method_num(ball_num,box_num,least_num)<<endl;
}
}
}