Handshaking

来源:互联网 发布:国际聊天软件 编辑:程序博客网 时间:2024/05/17 17:58
Handshaking
题目链接:http://soj.me/show_problem.php?pid=1000&cid=1035

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)。具体可查看卡特兰数的介绍。