数学递推思想在程序中的应用(二)----------放球问题

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;
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值