hdu 1133 Buy the Ticket(卡特兰数+大整数)

10 篇文章 0 订阅

题目原文:http://acm.hdu.edu.cn/showproblem.php?pid=1133

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.

解题思路:问题和Catalan数本质基本相同,所以可以借鉴卡特兰数的证明思路,先确定所有排列情况C(m+n,m)。

然后考虑不满足的情况,也就是必定存在一个奇数位前2*k+1个数中有k+1个0,k个1.而此时若将后面所有数位的0-1交换,可以构造出一个不满足题意的情况。也就是在m+n个位置选出m+1个位置放0.

这里重点讲一下这两者的等效性。

首先如果存在m+1个0,则肯定可以构造出不合法的情况。因为这种情况下1只有n-1个,所以最多只需要n个0就可以达到要求。

而对于每一种不合法的情况按照上文那种变换方式一定可以转化为存在m+1个0的情况。所以两者等价。

所以最后的公式为:

【注意】1、阶乘会爆longlong,所以最好用Java写一下大整数。

             2、特殊处理0!的情况

AC代码:

import java.util.*;
import java.math.*;
public class Main{
        public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int cnt = 1;
        BigInteger []factor = new BigInteger[230];
        factor[0] = BigInteger.ONE;
        for(int i = 1; i<=205; i++){
            factor[i] = factor[i-1].multiply(BigInteger.valueOf(i));
        }
        while(true){
            int m = sc.nextInt();
            int n = sc.nextInt();
            if(m+n==0)    break;
            System.out.println("Test #"+(cnt++)+":");
            if(m<n){
                System.out.println(0);
                continue;
            }
            else if(n==0){
                System.out.println(factor[m]);
                continue;
            }
            BigInteger ans = factor[m+n].divide(factor[m]).divide(factor[n]);
            //System.out.println(ans);
            ans = ans.subtract(factor[m+n].divide(factor[m+1]).divide(factor[n-1]));
            //System.out.println(ans);
            ans = ans.multiply(factor[m]).multiply(factor[n]);
            System.out.println(ans);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值