hdu1134Game of Connections(卡特兰数)

本文介绍了一个经典的组合数学问题——游戏连线问题。该问题要求计算在2n个点中,不相交地两两连接所有点的方法数量。通过分析得出,此问题的答案与卡特兰数密切相关,并给出了使用递推公式计算卡特兰数的Java实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Game of Connections

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5606    Accepted Submission(s): 3126

http://acm.hdu.edu.cn/showproblem.php?pid=1134
 

Problem Description

This is a small but ancient game. You are supposed to write down the numbers 1, 2, 3, ... , 2n - 1, 2n consecutively in clockwise order on the ground to form a circle, and then, to draw some straight line segments to connect them into number pairs. Every number must be connected to exactly one another. And, no two segments are allowed to intersect.

It's still a simple game, isn't it? But after you've written down the 2n numbers, can you tell me in how many different ways can you connect the numbers into pairs? Life is harder, right?

 

 

Input

Each line of the input file will be a single positive number n, except the last line, which is a number -1. You may assume that 1 <= n <= 100.

 

 

Output

For each n, print in a single line the number of ways to connect the 2n numbers into pairs.

 

 

Sample Input

2

3

-1

 

 

Sample Output

2

5

 

题意:输入n,有2n个点,把他们两两相连且不想交,有几种连法?

思路:画图分析得:1-n:1,2,5,14,42...  是卡特兰数,用公式。

代码:

import java.util.*;
import java.math.*;
public class game {
	public static void main(String[] args) {
		Scanner cin=new Scanner(System.in);
		while(cin.hasNext()) {
			int n=cin.nextInt();
			if(n==-1)
				break;
			BigInteger sum;
			BigInteger a=BigInteger.valueOf(1);
			BigInteger b=BigInteger.valueOf(2);
			if(n==1) {
				sum=a;
			}
			else if(n==2) {
				sum=b;
			}
			else {
				sum=b;
				for(int i=3;i<=n;i++) {
					int c=4*i-2;
					BigInteger d=BigInteger.valueOf(c);
					sum=sum.multiply(d);
					int e=i+1;
					BigInteger f=BigInteger.valueOf(e);
					sum=sum.divide(f);
					
				}
			}
			System.out.println(sum);
		}
		cin.close();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值