題目:
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different.
Perform all calculations in the 64-bit type: long long for С/С++, int64 for Delphi and long for Java.
The only line of the input data contains three integers n, m, t (4 ≤ n ≤ 30, 1 ≤ m ≤ 30, 5 ≤ t ≤ n + m).
Find the required number of ways.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
5 2 5
10
4 3 5
3
利用組合數遞推公式:C(n, m) = C(n - 1, m - 1) + C(n - 1, m) 對應最後一個選或者不選的情況
代碼:
#include<bits/stdc++.h>
using namespace std;
const int maxn=70;///只開到35的話 20 20 40 這組樣例會因爲越界報錯
__int64 n,m,t;
__int64 c[maxn][maxn];
int main(){
memset(c,0,sizeof(c));
c[0][0]=1;
for(int i=1;i<=30;++i){
c[i][0]=c[i][i]=1;
for(int j=1;j<=i;++j){
c[i][j]=c[i-1][j-1]+c[i-1][j];
}
}
/*for(int i=0;i<=30;++i){
for(int j=0;j<=30;++j){
cout<<c[i][j]<<" ";
}
cout<<endl;
}*/
scanf("%I64d%I64d%I64d",&n,&m,&t);
__int64 ans=0;
for(__int64 i=4;i<t;++i){
ans+=c[n][i]*c[m][t-i];///若判一下i和n的關係以及m和t-1的關係數組就可以開小一些
}
printf("%I64d\n",ans);
return 0;
}
也可以使用遞推公式每次算一下,不過會慢一些:
#include<bits/stdc++.h>
using namespace std;
__int64 n,m,t;
__int64 C(__int64 n,__int64 m){
__int64 ans=1;
for(__int64 i=1;i<=m;++i){
ans*=(n-i+1);
ans/=i;
}
return ans;
}
int main(){
scanf("%I64d%I64d%I64d",&n,&m,&t);
__int64 ans=0;
for(__int64 i=4;i<t;++i){
ans+=C(n,i)*C(m,t-i);
}
printf("%I64d\n",ans);
return 0;
}