hdu5184 给出(和)前半段问后面有多少种加括号方法使合法:类似卡特兰数+逆元模板

题解说的很好呀==

就是拿50和100的买票多少种方案==

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 using namespace std;
 5 #define LL long long
 6 #define MOD 1000000007
 7 LL fac[1000005];
 8 char s[1000005];
 9 LL inv(LL a,LL mod)
10 {
11   LL b=mod,b0=b,t,q,x0=0,x1=1;
12   if (b==1) return 1;
13   while (a>1)
14   {
15     q=a/b;
16     t=b,b=a%b,a=t;
17     t=x0,x0=x1-q*x0,x1=t;
18   }
19   if (x1<0) x1+=b0;
20   return x1;
21 }
22 int main()
23 {
24   LL n,len,a,b,i,judge,p,q,x;
25   fac[0]=1;
26   for (i=1;i<=1000000;i++) fac[i]=fac[i-1]*i%MOD;
27   while (~scanf("%I64d",&n))
28   {
29     scanf("%s",s);
30     len=strlen(s);
31     a=b=0; judge=1;
32     for (i=0;i<len;i++)
33     {
34       if (s[i]=='(') a++;
35       else b++;
36      if (a<b) judge=0; 
37     }
38     if (judge==0||a>n/2||b>n/2||n%2) {
39       printf("0\n"); 
40       continue;
41     }
42     p=n/2-b; q=n/2-a;
43     x=(p-q+1)*fac[p+q]%MOD;
44     x=x*inv(p+1,MOD)%MOD;
45     x=x*inv(fac[p],MOD)%MOD;
46     x=x*inv(fac[q],MOD)%MOD;
47     printf("%I64d\n",x);
48   }
49   return 0;
50 }
View Code

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5184

posted on 2015-03-15 20:39  xiao_xin  阅读(146)  评论(0编辑  收藏  举报

导航