Handshaking
来源:互联网 发布:国际聊天软件 编辑:程序博客网 时间:2024/05/17 17:58
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.
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 N (2<=N<=2000), indicating the number of persons.
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.
4
2
4
6
8
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)。具体可查看卡特兰数的介绍。
- Handshaking
- Handshaking
- 用python的win32com模块替换word中的文字搞定批量打印奖状
- VirtualBox Notes
- 《Expert MySQL》翻译——chapter2.解剖数据库系统(3)
- hdoj_2029 Palindromes _easy version
- jz2440使用tftp下载笔记
- Handshaking
- 将十六进制的文本转换为nsmutabledata
- 谈谈PEG与高增长的关系
- hadoop中的机架感知(Rack aware)
- 借我一双慧眼-------辨别财务造假
- 作为一个MYSQL DBA需要了解的知识
- FTP无法连接解决办法
- Android 动画详解之Tween动画
- 《Expert MySQL》翻译——chapter2.解剖数据库系统(2)