Handshaking

Handshaking

Description

N (N is even) persons stand around a round table. They make handshakes. Every person shakes the hand with one and exactly one of other persons. All handshakes are made at the same time. Your task is to calculate how many ways of handshaking can be made if arm crossing is not allowed.

 

For example, for N = 4, there are two ways of handshaking as follows.

The following way of handshaking is not allowed, because arm crossing happens.

 

Input

The input begins with a line containing an integer T (T<=1000), which indicates the number of test cases. The following T lines each contain an even number (2<=N<=2000), indicating the number of persons.

Output

For each case, output the number of ways. The answer may be very large, so just output the remainder of the answer after divided by 1000000007.

Sample Input
4
2
4
6
8
Sample Output
1
2
5
14


握手:圆桌上n个人,n为偶数,圆桌上两两握手,要求不出现交叉握手情况,求总共有多少种握手方法。

分析:圆桌上,挑出一对人握手(1跟i号,i必须为偶数,否则有一边会剩下奇数个人),握手连线将圆桌划分为两个部分,这两个部分内部两两握手,根据乘法原理,可得总的方案数。i有n/2种选择,累加。即卡特兰公式。

根据卡特兰数规律,利用公式f(n) = f(0)*f(n-2) + f(2)*f(n-4) + f(4)*f(n-6) + ......f(n-4)*f(2) + f(n-2)*f(0),可求得。

(1)简单回溯,注意模1000000007

#include<iostream>
#include<cstring>
using namespace std;
long long  note[2005];

void check( )
{
     memset(note,0,sizeof(note));
    //f(n) = f(0)*f(n-2) + f(2)*f(n-4) + f(4)*f(n-6) + ......f(n-4)*f(2) + f(n-2)*f(0)
     note[0]=1;
     note[2]=1;
     for(int x=4;x<=2005;x=x+2)
     {
     int sum1=0;
     for(int y=0;y<2005;y=y+2)
     {
      sum1 += note[y]*note[x-2-y]%1000000007;
      sum1 = sum1%1000000007;
     }
     note[x]=sum1;
     }
}
      
int main()
{
    check();
    int time;
    cin>>time;
    while(time--)
    {
    int num;
    cin>>num;
    cout<<note[num]<<endl;
    }
    return 0;
}

(2)DP,其实与回溯基本一样

#include <iostream>
 #include <cstring>
 #include <string>
 using namespace std;
 long long dp[2005];
 void Count( )
 {
     memset( dp, 0, sizeof dp ); 
     dp[0]=1; dp[2]=1;
     for( int i=4; i<=2001; i+=2 )
         for( int j=2; j<=i; ++j ){
             dp[i]+=(dp[j-2]*dp[i-j])%1000000007;
             dp[i]%=1000000007;
         }
 }
 int main( )
 {
     Count( );
     int T, N;
     scanf( "%d", &T );
     while( T -- ){
         scanf( "%d", &N );
         printf( "%lld\n", dp[N] );
     } 
     return 0;
 }                                 


总结:主要是分析得出状态方程,即公式f(n) = f(0)*f(n-2) + f(2)*f(n-4) + f(4)*f(n-6) + ......f(n-4)*f(2) + f(n-2)*f(0)。具体可查看卡特兰数的介绍。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值