hdu 1133 Buy the Ticket
Buy the Ticket
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1911 Accepted Submission(s): 795
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.
3 1
3 3
0 0
6
Test #2:
18
Test #3:
180
如果有这么一个序列 0101101001001111..........
当第K个位置出现1的个数多余0的个数时就是一个不合法序列了
假设m=4 n=3的一个序列是:0110100 显然,它不合法, 现在我们把它稍微变化一下:
把第二个1(这个1前面的都是合法的)后面的所有位0变成1,1变成0
就得到 0111011 这个序列1的数量多于0的数量, 显然不合法, 但现在的关键不是看这个序列是不是合法的
关键是:它和我们的不合法序列 0110100 成一一对应的关系
也就是说任意一个不合法序列(m个0,n个1), 都可以由另外一个序列(n-1个0和m+1个1)得到
另外我们知道,一个序列要么是合法的,要么是不合法的
所以,合法序列数量 = 序列总数量 - 不合法序列的总量
序列总数可以这样计算m+n 个位置中, 选择 n 个位置出来填上 1, 所以是 C(m+n, n)
不合法序列的数量就是: m+n 个位置中, 选择 m+1 个位置出来填上 1 所以是 C(m+n, m+1)
然后每个人都是不一样的,所以需要全排列 m! * n!
所以最后的公式就是(C(m+n, n)-C(m+n, m+1))*m!*n! 化简后为 (m+n)!*(m-n+1)/(m+1);
#include <cstdlib> #include <iostream> #define MAX 102 using namespace std; int factor[205][MAX]={0}; int sim[201]={0}; void multiply(int s[],int Max,int b) { int ans=0; for(int i=Max;i>=0;i--) { ans+=s[i]*b; s[i]=ans%10000; ans/=10000; } } void div(int s[],int Max,int b) { int ans=0; for(int i=0;i<=Max;i++) { ans=ans*10000+s[i]; s[i]=ans/b; ans%=b; } } int getfactor(){ int i; factor[0][MAX-1]=factor[1][MAX-1]=1; for(i=2;i<=203;i++){ memcpy(factor[i],factor[i-1],MAX*sizeof(int));//this has a falut that i have replace memcpy by strcpy! multiply(factor[i],MAX-1,i); } return 0; } int output(int *s,int k){ int i=1; printf("Test #%d:\n",k); while(s[i]==0&&i<MAX) i++; printf("%d",s[i++]); for(;i<MAX;i++) printf("%04d",s[i]); printf("\n"); return 0; } int main(int argc, char *argv[]) { int m,n,i,k=1; getfactor(); while(scanf("%d %d",&m,&n),m+n){ /*for(i=1;i<=MAX;i++){ for(int j=1;j<MAX;j++) cout<<factor[i][j]; cout<<endl; }*/ if(n>m){ printf("Test #%d:\n",k++); printf("0\n"); //别忘记了 判断这种情况, //当初为了这个BUG找了好苦,5555.... continue; } memcpy(sim,factor[m+n],sizeof(int)*MAX); multiply(sim,MAX-1,m-n+1); div(sim,MAX-1,m+1); output(sim,k); k++; } system("PAUSE"); return EXIT_SUCCESS; }