Description
The "Harry Potter and the Goblet of Fire" will be on show in the next few days. As a crazy fan of Harry Potter, you will go to the cinema and have the first sight, won’t you?
Suppose the cinema only has one ticket-office and the price for per-ticket is 50 dollars. The queue for buying the tickets is consisted of m + n persons (m persons each only has the 50-dollar bill and n persons each only has the 100-dollar bill).
Now the problem for you is to calculate the number of different ways of the queue that the buying process won't be stopped from the first person till the last person.
Note: initially the ticket-office has no money.
The buying process will be stopped on the occasion that the ticket-office has no 50-dollar bill but the first person of the queue only has the 100-dollar bill.Input
The input file contains several test cases. Each test case is made up of two integer numbers: m and n. It is terminated by m = n = 0. Otherwise, m, n <=100.
Output
For each test case, first print the test number (counting from 1) in one line, then output the number of different ways in another line.
Sample Input
3 0
3 1
3 3
0 0
Sample Output
Test #1: 6
Test #2: 18
Test #3: 180
题解:
m人有50元,n人有100元,收营员要拿收到的50找给100,如果没有50就停止,求符合条件序列的个数。
m < n 时 不存在合法方案
当 m >= n 时
合法排列有定有 m!×n!×C(m,m+n)种排法
而有 m!×n!×C(m+1,m+n) 非法排法 (从有1个50的前边至少多1个100)
所以有合法排法 m!×n!×(C(m,m+n)−C(m+1,m+n))= (m+n)!×(m−n+1)/(m+1)不懂的请看:卡特兰数
证明:
(1) 对于一个m个0,n个1的不合法序列,设其最小不合法子列为[0,a).,其中有x+1个1, x个0(1和0的个数只相差1由“最小性”保证)。则剩余子列中(n-x-1)个1, (m-x)个0. 将剩余子列翻转,翻转剩余子列有(n-x-1)个0, (m-x)个1. 如此得到的序列1的个数=(x+1) + (m-x)=m+1, 0的个数=(x) + (n-x-1)=n-1.
(2) 对于一个m+1个1,n-1个0的序列,必然存在一个从0开始的子列,其中1的个数比0的个数多1。将这个子列作为“不合法子列”(x+1个1, x个0),将剩余子列( (m-x)个1, (n-x-1)个0)翻转得到翻转子列( (m-x)个0, (n-x-1)个1),与“不合法子列”拼接可以得到一个m个0, n个1的序列,由于该序列存在前述“不合法子列”,该序列是不合法的
由此我们证明了任意一个m个0,n个1的不合法序列(m>=n)与一个m+1个1,n-1个0的序列一一对应,因此计算不合法序列个数也就是计算m+1个1,n-1个0的序列个数=C(m+1)(m+n)
代码如下:
import java.math.*;
import java.util.*;
public class Main
{
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
int cnt=1;
while(true){
int a,b;
a=cin.nextInt();
b=cin.nextInt();
if(a==0||b==0)
{
break;
}
System.out.println("Test #"+(cnt++)+":");
BigDecimal big;
if(a>=b)
{
big=BigDecimal.ONE;
for(int i=1; i<=(a+b); i++)
big=big.multiply(new BigDecimal(i));
big=big.multiply(new BigDecimal(a-b+1));
big=big.divide(new BigDecimal(a+1));
}
else
big=BigDecimal.ZERO;
System.out.println(big);
}
}
}