牛客 - 弦(卡特兰数)
生活随笔
收集整理的這篇文章主要介紹了
牛客 - 弦(卡特兰数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給定一個圓,圓上有2N個互不重疊的點。每次操作隨機選擇兩個先前未選擇過的點連一條弦,共連成N條弦,求所有弦不交的概率。
題目分析:圓內連弦是卡特蘭數的經典應用,如果將最后的概率視為分子除以分母的話,那么分子就是可行方案數,分母是總共的方案數,分子自然就是卡特蘭數了,而分母我們可以想象為先選取兩個點連弦,再不斷選取剩下點中的兩個點連弦,則公式就是,注意,這里計算出來的方案數是這 n 條弦排列組合后的答案,需要除以 n! 才是組合數的答案
然后配合逆元實現就好了
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> using namespace std;typedef long long LL;typedef unsigned long long ull;const LL inf=0x3f3f3f3f;const int N=2e7+100;const int mod=1e9+7;int fac[N],inv[N];LL q_pow(LL a,LL b) {LL ans=1;while(b){if(b&1)ans=ans*a%mod;a=a*a%mod;b>>=1;}return ans; }void init()//初始化階乘和逆元 {fac[0]=1;for(int i=1;i<N;i++)fac[i]=1LL*fac[i-1]*i%mod;inv[N-1]=q_pow(1LL*fac[N-1],mod-2);for(int i=N-2;i>=0;i--)inv[i]=1LL*inv[i+1]*(i+1)%mod; }LL C(int n,int m) {return 1LL*fac[n]*inv[n-m]%mod*inv[m]%mod; }LL cal(int n)//卡特蘭數(分子) {return (1LL*C(2*n,n)-C(2*n,n-1)+mod)%mod; }LL cal2(int n)//計算分母 {LL ans=1;for(int i=n*2;i>0;i-=2)ans=ans*C(i,2)%mod;return ans*inv[n]%mod; }int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);init();int n;scanf("%d",&n);printf("%lld\n",cal(n)*q_pow(cal2(n),mod-2)%mod);return 0; }?
總結
以上是生活随笔為你收集整理的牛客 - 弦(卡特兰数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客 - 车辆调度(dfs)
- 下一篇: 牛客 - 张老师的旅行(dp)