Buy the Ticket(卡特兰数 + JAVA大数)

来源:互联网 发布:门禁发卡软件 编辑:程序博客网 时间:2024/06/05 04:18

Buy the Ticket
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7250 Accepted Submission(s): 3038

Problem 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元用 0表示 100 元用 1 表示 这样就可以和卡特兰数结合起来了
假设有m = 4 n = 3;
0101100 这是一个非法的序列 在第三个1的位置时电影院就找不开了 我们这时对从这个位置的后面一个取反 变为0101111 我们可以看到有 2 个0 5 个1 我们假设序列在第k个位置出现了找零找不开了 即不合法 那么在第k个位置之前0和1的个数一定是相等的 均为 (k-1)/2个 所以第k个位置后面0的个数为 m - (k-1)/2 1的个数为n - (k-1)/2 -1 ;经过取反之后序列中0的个数为 (k-1)/2 + n - (k-1)/2 -1 = n-1个 1的个数为(k-1)/2 + 1 + m - (k-1)/2 = m +1 个 所以这里我们就得到了一个规律 任何一个非法的序列都是由 n-1 个0 m +1 个1组成的
所以总的序列种数 = 不合法的总数 + 合法的总数
所以合法的总数 = 序列总数 - 不合法的总数 =( C(m+n,n) - C(m+n,m+1))m! *n! = (m+n)! (m+1 -n)/(m+1)
最后一点还需要判断 当n>m时 总的种数一定为0……..

import java.math.BigInteger;import java.util.Scanner;public class Main {    public static void main(String[] args) {        int m,n;        Scanner cin = new Scanner(System.in);        int cnt = 1;        while(cin.hasNext())        {            m = cin.nextInt();            n = cin.nextInt();            if(n==0&&m ==0)                break;            System.out.println("Test #"+cnt+++":");            if(n>m)            {                System.out.println(0);                continue;            }            BigInteger sum = BigInteger.ONE;            for(int i = 2;i<= (m + n);i++)            {                sum = sum.multiply(BigInteger.valueOf(i));            }            System.out.println(sum.multiply(BigInteger.valueOf(m + 1 - n)).divide(BigInteger.valueOf(m +1)));        }    }}
阅读全文
0 0
原创粉丝点击